Skip to content

Instantly share code, notes, and snippets.

@berarma
Last active June 29, 2022 12:15
Show Gist options
  • Save berarma/5ea4ca9ff909df0a1017ef73250ef647 to your computer and use it in GitHub Desktop.
Save berarma/5ea4ca9ff909df0a1017ef73250ef647 to your computer and use it in GitHub Desktop.
RefreshAssociationTrait for CakePHP3
<?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);
}
}
}
}
@larsgw
Copy link

larsgw commented Jun 29, 2022

Can I adapt this code in a project?

@berarma
Copy link
Author

berarma commented Jun 29, 2022

Can I adapt this code in a project?

Of course, go ahead.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment