Guest User

Untitled

a guest
Jul 19th, 2018
96
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 8.75 KB | None | 0 0
  1. <?php
  2. namespace App\Model;
  3.  
  4. use Cake\ORM\Entity;
  5.  
  6. trait RefreshAssociationsTrait
  7. {
  8. public function refreshAssociations(Entity $entity, array $associations = null)
  9. {
  10. if ($associations === null) {
  11. $associations = $this->associations()->keys();
  12. }
  13.  
  14. foreach ($associations as $table => $options) {
  15. if (is_int($table)) {
  16. $table = $options;
  17. $options = [];
  18. }
  19. if (is_string($table)) {
  20. if (strpos($table, '.') !== false) {
  21. list($table, $secondary) = explode('.', $table, 2);
  22. if (empty($options)) {
  23. $options = [$secondary];
  24. } else {
  25. $options = [$secondary => $options];
  26. }
  27. }
  28. }
  29.  
  30. $association = $this->association($table);
  31. $type = $association->type();
  32. $foreignKey = $association->getForeignKey();
  33. $property = $association->getProperty();
  34. $target = $association->getTarget();
  35.  
  36. if (in_array($type, [$association::ONE_TO_ONE, $association::MANY_TO_ONE])) {
  37. if (!$entity->dirty($foreignKey)) {
  38. continue;
  39. }
  40. $foreignId = $entity->get($foreignKey);
  41. if ($foreignId === null) {
  42. $value = null;
  43. } else {
  44. $value = $target->get($foreignId, ['contain' => $options]);
  45. }
  46. $entity->set($property, $value);
  47. } elseif (!empty($options)) {
  48. $target->loadInto($entity->get($property), $options);
  49. }
  50. }
  51. }
  52. }
Add Comment
Please, Sign In to add comment