Last active
June 29, 2022 12:15
-
-
Save berarma/5ea4ca9ff909df0a1017ef73250ef647 to your computer and use it in GitHub Desktop.
RefreshAssociationTrait for CakePHP3
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
namespace App\Model\Table; | |
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(); | |
$values = $entity->get($property); | |
$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($values) && !empty($options)) { | |
$target->loadInto($values, $options); | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Of course, go ahead.