Skip to content

Commit

Permalink
Fixing issue with extra association conditions being applied on the m…
Browse files Browse the repository at this point in the history
…arshaller

closes #6534
  • Loading branch information
lorenzo committed May 11, 2015
1 parent 2876210 commit 53d327a
Show file tree
Hide file tree
Showing 2 changed files with 51 additions and 5 deletions.
15 changes: 10 additions & 5 deletions src/ORM/Marshaller.php
Original file line number Diff line number Diff line change
Expand Up @@ -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);

Expand Down
41 changes: 41 additions & 0 deletions tests/TestCase/ORM/MarshallerTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down

0 comments on commit 53d327a

Please sign in to comment.