Skip to content

Commit

Permalink
Merge pull request #6261 from cjquinn/feature-belongstomany-mixed-data
Browse files Browse the repository at this point in the history
Feature belongsToMany mixed data
  • Loading branch information
lorenzo committed Apr 6, 2015
2 parents 3597048 + f49e7a4 commit 0333639
Show file tree
Hide file tree
Showing 2 changed files with 63 additions and 8 deletions.
22 changes: 14 additions & 8 deletions src/ORM/Marshaller.php
Expand Up @@ -276,20 +276,26 @@ protected function _belongsToMany(Association $assoc, array $data, $options = []
}
$data = array_values($data);

// Accept [ [id => 1], [id = 2] ] style.
$primaryKey = array_flip($assoc->target()->schema()->primaryKey());
if (array_intersect_key($primaryKey, current($data)) === $primaryKey) {
$primaryCount = count($primaryKey);
$query = $assoc->find();
foreach ($data as $row) {
$records = [];

foreach ($data as $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);
}
} else {
$records[] = $this->one($row, $options);
}
$records = $query->toArray();
} else {
$records = $this->many($data, $options);
}

if (isset($query)) {
$records = array_merge($records, $query->toArray());
}

$joint = $assoc->junction();
Expand Down
49 changes: 49 additions & 0 deletions tests/TestCase/ORM/MarshallerTest.php
Expand Up @@ -557,6 +557,55 @@ public function testOneBelongsToManyJoinDataAssociatedWithIds()
$this->assertEquals($data['tags'][5]['_joinData']['user']['username'], $result->tags[1]->_joinData->user->username);
}

/**
* Test belongsToMany association with mixed data array
*
* @return void
*/
public function testBelongsToManyWithMixedData()
{
$data = [
'title' => 'My title',
'body' => 'My content',
'author_id' => 1,
'tags' => [
[
'name' => 'tag4'
],
[
'name' => 'tag5'
],
[
'id' => 1
]
]
];

$articles = TableRegistry::get('Articles');
$articles->belongsToMany('Tags');

$tags = TableRegistry::get('Tags');

$article = $articles->newEntity($data, [
'associated' => [
'Tags'
]
]);

$this->assertEquals($data['tags'][0]['name'], $article->tags[0]->name);
$this->assertEquals($data['tags'][1]['name'], $article->tags[1]->name);
$this->assertEquals($article->tags[2], $tags->get(1));

$this->assertEquals($article->tags[0]->isNew(), true);
$this->assertEquals($article->tags[1]->isNew(), true);
$this->assertEquals($article->tags[2]->isNew(), false);

$tagCount = $tags->find()->count();
$articles->save($article);

$this->assertEquals($tagCount + 2, $tags->find()->count());
}

/**
* Test HasMany association with _ids attribute
*
Expand Down

0 comments on commit 0333639

Please sign in to comment.