Skip to content
Permalink
Browse files

Fixing issue with extra association conditions being applied on the m…

…arshaller

closes #6534
  • Loading branch information...
lorenzo committed May 11, 2015
1 parent 2876210 commit 53d327aa1bf921f32ad2ebdd5a63843a5dadd831
Showing with 51 additions and 5 deletions.
  1. +10 −5 src/ORM/Marshaller.php
  2. +41 −0 tests/TestCase/ORM/MarshallerTest.php
@@ -282,22 +282,27 @@ protected function _belongsToMany(Association $assoc, array $data, $options = []
$primaryKey = array_flip($assoc->target()->schema()->primaryKey());
$records = [];
$conditions = [];
$primaryCount = count($primaryKey);
foreach ($data as $i => $row) {
if (array_intersect_key($primaryKey, $row) === $primaryKey) {
if (!isset($query)) {
$primaryCount = count($primaryKey);
$query = $assoc->find();
}
$keys = array_intersect_key($row, $primaryKey);
if (count($keys) === $primaryCount) {
$query->orWhere($keys);
$conditions[] = $keys;
}
} else {
$records[$i] = $this->one($row, $options);
}
}
if (!empty($conditions)) {
$query = $assoc->target()->find();
$query->andWhere(function ($exp) use ($conditions) {
return $exp->or_($conditions);
});
}
if (isset($query)) {
$keyFields = array_keys($primaryKey);
@@ -1288,6 +1288,47 @@ public function testMergeBelongsToManyFromIdsWithConditions()
$this->assertInstanceOf('Cake\ORM\Entity', $result->tags[2]);
}
/**
* Tests that merging data to an entity containing belongsToMany as an array
* with additional association conditions works.
*
* @return void
*/
public function testMergeBelongsToManyFromArrayWithConditions()
{
$this->articles->belongsToMany('Tags', [
'conditions' => ['ArticleTags.article_id' => 1]
]);
$this->articles->Tags->eventManager()
->on('Model.beforeFind', function($event, $query) use (&$called) {
$called = true;
return $query->where(['Tags.id >=' => 1]);
});
$entity = new Entity([
'title' => 'No tags',
'body' => 'Some content here',
'tags' => []
]);
$data = [
'title' => 'Haz moar tags',
'tags' => [
['id' => 1],
['id' => 2]
]
];
$entity->accessible('*', true);
$marshall = new Marshaller($this->articles);
$result = $marshall->merge($entity, $data, ['associated' => ['Tags']]);
$this->assertCount(2, $result->tags);
$this->assertInstanceOf('Cake\ORM\Entity', $result->tags[0]);
$this->assertInstanceOf('Cake\ORM\Entity', $result->tags[1]);
$this->assertTrue($called);
}
/**
* Tests that merging data to an entity containing belongsToMany and _ids
* will ignore empty values.

0 comments on commit 53d327a

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