Skip to content

Commit

Permalink
In BelongsToMany, linking entities will set the junction table regist…
Browse files Browse the repository at this point in the history
…ry alias
  • Loading branch information
nojimage committed Oct 2, 2018
1 parent 9110e6c commit e4af9c4
Show file tree
Hide file tree
Showing 2 changed files with 43 additions and 2 deletions.
4 changes: 2 additions & 2 deletions src/ORM/Association/BelongsToMany.php
Original file line number Diff line number Diff line change
Expand Up @@ -825,12 +825,12 @@ protected function _saveLinks(EntityInterface $sourceEntity, $targetEntities, $o
$targetPrimaryKey = (array)$target->getPrimaryKey();
$bindingKey = (array)$this->getBindingKey();
$jointProperty = $this->_junctionProperty;
$junctionAlias = $junction->getAlias();
$junctionRegistryAlias = $junction->getRegistryAlias();

foreach ($targetEntities as $e) {
$joint = $e->get($jointProperty);
if (!$joint || !($joint instanceof EntityInterface)) {
$joint = new $entityClass([], ['markNew' => true, 'source' => $junctionAlias]);
$joint = new $entityClass([], ['markNew' => true, 'source' => $junctionRegistryAlias]);
}
$sourceKeys = array_combine($foreignKey, $sourceEntity->extract($bindingKey));
$targetKeys = array_combine($assocForeignKey, $e->extract($targetPrimaryKey));
Expand Down
41 changes: 41 additions & 0 deletions tests/TestCase/ORM/Association/BelongsToManyTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -599,6 +599,47 @@ public function testLinkSuccessWithMocks()
$this->assertSame($entity->test, $tags);
}

/**
* Tests that linking entities will set the junction table registry alias
*
* @return void
*/
public function testLinkSetSourceToJunctionEntities()
{
$connection = ConnectionManager::get('test');
$joint = $this->getMockBuilder('\Cake\ORM\Table')
->setMethods(['save', 'getPrimaryKey'])
->setConstructorArgs([['alias' => 'ArticlesTags', 'connection' => $connection]])
->getMock();
$joint->setRegistryAlias('Plugin.ArticlesTags');

$config = [
'sourceTable' => $this->article,
'targetTable' => $this->tag,
'through' => $joint,
];

$assoc = new BelongsToMany('Tags', $config);
$opts = ['markNew' => false];
$entity = new Entity(['id' => 1], $opts);
$tags = [new Entity(['id' => 2], $opts)];

$joint->method('getPrimaryKey')
->will($this->returnValue(['article_id', 'tag_id']));

$joint->expects($this->once())
->method('save')
->will($this->returnCallback(function (Entity $e, $opts) {
$this->assertSame('Plugin.ArticlesTags', $e->getSource());

return $e;
}));

$this->assertTrue($assoc->link($entity, $tags));
$this->assertSame($entity->tags, $tags);
$this->assertSame('Plugin.ArticlesTags', $entity->tags[0]->get('_joinData')->getSource());
}

/**
* Test liking entities having a non persisted source entity
*
Expand Down

0 comments on commit e4af9c4

Please sign in to comment.