Skip to content

Commit

Permalink
Refatoring Table::loadInto() for start accepting a list of objects
Browse files Browse the repository at this point in the history
  • Loading branch information
lorenzo committed Jun 28, 2015
1 parent 37779c4 commit 11bb0c8
Showing 1 changed file with 34 additions and 9 deletions.
43 changes: 34 additions & 9 deletions src/ORM/Table.php
Expand Up @@ -16,6 +16,7 @@

use ArrayObject;
use BadMethodCallException;
use Cake\Collection\Collection;
use Cake\Core\App;
use Cake\Database\Connection;
use Cake\Database\Schema\Table as Schema;
Expand Down Expand Up @@ -2181,22 +2182,46 @@ public function buildRules(RulesChecker $rules)
return $rules;
}

public function loadInto($object, array $contain)
public function loadInto($objects, array $contain)
{
$returnSingle = false;

if ($objects instanceof EntityInterface) {
$objects = [$objects];
$returnSingle = true;
}

$objects = new Collection($objects);
$primaryKey = $this->primaryKey();
$method = is_string($primaryKey) ? 'get' : 'extract';

$keys = $objects->map(function ($entity) use ($primaryKey, $method) {
return $entity->{$method}($primaryKey);
});

$query = $this
->find()
->where(['id' => $object->id])
->where(function ($exp) use ($primaryKey, $keys) {
return $exp->in($this->primaryKey(), $keys->toList());
})
->contain($contain);

$loaded = $query->first();
$assocs = $this->associations();
foreach ($query->contain() as $assoc => $config) {
$property = $assocs->get($assoc)->property();
$object->set($property, $loaded->get($property), ['useSetters' => false]);
$object->dirty($property, false);
}
$contain = $query->contain();
$results = $query->indexBy($primaryKey)->toArray();
$objects = $objects
->indexBy($primaryKey)
->map(function ($object, $key) use ($results, $contain, $assocs) {
$loaded = $results[$key];
foreach ($contain as $assoc => $config) {
$property = $assocs->get($assoc)->property();
$object->set($property, $loaded->get($property), ['useSetters' => false]);
$object->dirty($property, false);
}
return $object;
});

return $object;
return $returnSingle ? $objects->first() : $objects->toList();
}

/**
Expand Down

0 comments on commit 11bb0c8

Please sign in to comment.