Skip to content

Commit

Permalink
Merge pull request #2556 from cakephp/3.0-habtm-ids
Browse files Browse the repository at this point in the history
3.0 - Add ability to handle a list of ids for belongs to many.
  • Loading branch information
lorenzo committed Dec 27, 2013
2 parents d43ee23 + 57cceef commit b82cc15
Show file tree
Hide file tree
Showing 2 changed files with 43 additions and 1 deletion.
22 changes: 22 additions & 0 deletions Cake/ORM/Marshaller.php
Expand Up @@ -153,6 +153,10 @@ public function many(array $data, $include = []) {
* @return array An array of built entities.
*/
protected function _belongsToMany(Association $assoc, array $data, $include = []) {
if (isset($data['_ids']) && is_array($data['_ids'])) {
return $this->_loadBelongsToMany($assoc, $data['_ids']);
}

$records = $this->many($data, $include);
if (!in_array('_joinData', $include) && !isset($include['_joinData'])) {
return $records;
Expand All @@ -175,4 +179,22 @@ protected function _belongsToMany(Association $assoc, array $data, $include = []
return $records;
}

/**
* Loads a list of belongs to many from ids.
*
* @param Association $assoc The association class for the belongsToMany association.
* @param array $ids The list of ids to load.
* @return array An array of entities.
*/
protected function _loadBelongsToMany($assoc, $ids) {
$target = $assoc->target();
$primaryKey = (array)$target->primaryKey();
if (count($primaryKey) > 1) {
return [];
}
return $assoc->find('all')
->where([$primaryKey[0] . ' IN' => $ids])
->toArray();
}

}
22 changes: 21 additions & 1 deletion Cake/Test/TestCase/ORM/MarshallerTest.php
Expand Up @@ -48,7 +48,7 @@ class ProtectedArticle extends Entity {
*/
class MarshallerTest extends TestCase {

public $fixtures = ['core.article', 'core.user', 'core.comment'];
public $fixtures = ['core.tag', 'core.article', 'core.user', 'core.comment'];

/**
* setup
Expand Down Expand Up @@ -413,4 +413,24 @@ public function testManyAssociations() {
);
}

/**
* Test generating a list of entities from a list of ids.
*
* @return void
*/
public function testOneGenerateBelongsToManyEntitiesFromIds() {
$data = [
'title' => 'Haz tags',
'body' => 'Some content here',
'tags' => ['_ids' => [1, 2, 3]]
];
$marshall = new Marshaller($this->articles);
$result = $marshall->one($data, ['Tags']);

$this->assertCount(3, $result->tags);
$this->assertInstanceOf('Cake\ORM\Entity', $result->tags[0]);
$this->assertInstanceOf('Cake\ORM\Entity', $result->tags[1]);
$this->assertInstanceOf('Cake\ORM\Entity', $result->tags[2]);
}

}

0 comments on commit b82cc15

Please sign in to comment.