diff --git a/src/ORM/Table.php b/src/ORM/Table.php index 53b61eef13e..8fd2c4fa0f7 100644 --- a/src/ORM/Table.php +++ b/src/ORM/Table.php @@ -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; @@ -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(); } /**