Navigation Menu

Skip to content

Commit

Permalink
Making it possible to append additional links to a belongsToMany, this
Browse files Browse the repository at this point in the history
assumes that joint information is present
  • Loading branch information
lorenzo committed Nov 29, 2013
1 parent cdd24b9 commit 2c7026d
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 2 deletions.
4 changes: 2 additions & 2 deletions Cake/ORM/Association/BelongsToMany.php
Expand Up @@ -346,15 +346,14 @@ protected function _saveLinks(Entity $sourceEntity, $targetEntities, $options) {
$source = $this->source();
$entityClass = $pivot->entityClass();
$belongsTo = $pivot->association($target->alias());
$property = $belongsTo->property();
$foreignKey = (array)$this->foreignKey();
$assocForeignKey = (array)$belongsTo->foreignKey();
$targetPrimaryKey = (array)$target->primaryKey();
$sourcePrimaryKey = (array)$source->primaryKey();
$jointProperty = $target->association($pivot->alias())->property();

foreach ($targetEntities as $k => $e) {
$joint = $e->get($property);
$joint = $e->get($jointProperty);
if (!$joint) {
$joint = new $entityClass;
$joint->isNew(true);
Expand All @@ -372,6 +371,7 @@ protected function _saveLinks(Entity $sourceEntity, $targetEntities, $options) {
}

$e->set($jointProperty, $joint);
$e->dirty($jointProperty, false);
}

return true;
Expand Down
28 changes: 28 additions & 0 deletions Cake/Test/TestCase/ORM/TableTest.php
Expand Up @@ -2434,4 +2434,32 @@ public function testSaveCleanEntity() {
$this->assertSame($entity, $table->save($entity));
}

/**
* Integration test to show how to append a new tag to an article
*
* @group save
* @return void
*/
public function testBelongsToManyIntegration() {
$table = TableRegistry::get('articles');
$table->belongsToMany('tags');
$article = $table->find('all')->where(['id' => 1])->contain(['tags'])->first();
$tags = $article->tags;
$this->assertNotEmpty($tags);
$tags[] = new \TestApp\Model\Entity\Tag([
'name' => 'Something New'
]);
$article->tags = $tags;
$this->assertSame($article, $table->save($article));
$tags = $article->tags;
$this->assertCount(3, $tags);
$this->assertFalse($tags[2]->isNew());
$this->assertEquals(4, $tags[2]->id);
$this->assertEquals(1, $tags[2]->extraInfo->article_id);
$this->assertEquals(4, $tags[2]->extraInfo->tag_id);

$article = $table->find('all')->where(['id' => 1])->contain(['tags'])->first();
$this->assertEquals($tags, $article->tags);
}

}

0 comments on commit 2c7026d

Please sign in to comment.