Skip to content
Permalink
Browse files

Adding the possibility of having _ids field in a Hasmany association.

Signed-off-by: Luan Hospodarsky <luan.handrade@gmail.com>
  • Loading branch information...
mylux committed Mar 30, 2015
1 parent 5c4d1d7 commit ae6a1a2021930bddb258fcef96de3ef5ac2bb646
Showing with 32 additions and 3 deletions.
  1. +8 −3 src/ORM/Marshaller.php
  2. +24 −0 tests/TestCase/ORM/MarshallerTest.php
@@ -223,6 +223,11 @@ protected function _marshalAssociation($assoc, $value, $options)
if ($assoc->type() === Association::MANY_TO_MANY) {
return $marshaller->_belongsToMany($assoc, $value, (array)$options);
}
if ($assoc->type() === Association::ONE_TO_MANY && array_key_exists('_ids', $value)) {
if (is_array($value['_ids'])) {
return $this->_loadAssociatedByIds($assoc, $value['_ids']);
}
}
return $marshaller->many($value, (array)$options);
}
@@ -266,7 +271,7 @@ protected function _belongsToMany(Association $assoc, array $data, $options = []
$associated = isset($options['associated']) ? $options['associated'] : [];
$hasIds = array_key_exists('_ids', $data);
if ($hasIds && is_array($data['_ids'])) {
return $this->_loadBelongsToMany($assoc, $data['_ids']);
return $this->_loadAssociatedByIds($assoc, $data['_ids']);
}
if ($hasIds) {
return [];
@@ -313,7 +318,7 @@ protected function _belongsToMany(Association $assoc, array $data, $options = []
* @param array $ids The list of ids to load.
* @return array An array of entities.
*/
protected function _loadBelongsToMany($assoc, $ids)
protected function _loadAssociatedByIds($assoc, $ids)
{
$target = $assoc->target();
$primaryKey = (array)$target->primaryKey();
@@ -557,7 +562,7 @@ protected function _mergeBelongsToMany($original, $assoc, $value, $options)
$hasIds = array_key_exists('_ids', $value);
$associated = isset($options['associated']) ? $options['associated'] : [];
if ($hasIds && is_array($value['_ids'])) {
return $this->_loadBelongsToMany($assoc, $value['_ids']);
return $this->_loadAssociatedByIds($assoc, $value['_ids']);
}
if ($hasIds) {
return [];
@@ -557,6 +557,30 @@ public function testOneBelongsToManyJoinDataAssociatedWithIds()
$this->assertEquals($data['tags'][5]['_joinData']['user']['username'], $result->tags[1]->_joinData->user->username);
}
/**
* Test HasMany association with _ids attribute
*
* @return void
*/
public function testHasManyWithIds()
{
$data = [
'username' => 'lux',
'password' => 'passphrase',
'comments' => [
'_ids' => [1, 2]
]
];
$userTable = TableRegistry::get('Users');
$userTable->hasMany('Comments');
$commentTable = TableRegistry::get('Comments');
$user = $userTable->newEntity($data, ['associated' => ['Comments']]);
$this->assertEquals($user->comments[0], $commentTable->get(1));
$this->assertEquals($user->comments[1], $commentTable->get(2));
}
/**
* Test one() with deeper associations.
*

0 comments on commit ae6a1a2

Please sign in to comment.
You can’t perform that action at this time.