Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <?php
- namespace App\Model;
- use Cake\ORM\Entity;
- trait RefreshAssociationsTrait
- {
- public function refreshAssociations(Entity $entity, array $associations = null)
- {
- if ($associations === null) {
- $associations = $this->associations()->keys();
- }
- foreach ($associations as $table => $options) {
- if (is_int($table)) {
- $table = $options;
- $options = [];
- }
- if (is_string($table)) {
- if (strpos($table, '.') !== false) {
- list($table, $secondary) = explode('.', $table, 2);
- if (empty($options)) {
- $options = [$secondary];
- } else {
- $options = [$secondary => $options];
- }
- }
- }
- $association = $this->association($table);
- $type = $association->type();
- $foreignKey = $association->getForeignKey();
- $property = $association->getProperty();
- $target = $association->getTarget();
- if (in_array($type, [$association::ONE_TO_ONE, $association::MANY_TO_ONE])) {
- if (!$entity->dirty($foreignKey)) {
- continue;
- }
- $foreignId = $entity->get($foreignKey);
- if ($foreignId === null) {
- $value = null;
- } else {
- $value = $target->get($foreignId, ['contain' => $options]);
- }
- $entity->set($property, $value);
- } elseif (!empty($options)) {
- $target->loadInto($entity->get($property), $options);
- }
- }
- }
- }
Add Comment
Please, Sign In to add comment