Cake\ORM\Association\BelongsToMany::link PHP Method

    public function link(EntityInterface $sourceEntity, array $targetEntities, array $options = [])
    {
        $this->_checkPersistenceStatus($sourceEntity, $targetEntities);
        $property = $this->property();
        $links = $sourceEntity->get($property) ?: [];
        $links = array_merge($links, $targetEntities);
        $sourceEntity->set($property, $links);
        return $this->junction()->connection()->transactional(function () use($sourceEntity, $targetEntities, $options) {
            return $this->_saveLinks($sourceEntity, $targetEntities, $options);
        });
    }

Usage Example

示例#1
0
 /**
  * Tests that liking entities will validate data and pass on to _saveLinks
  *
  * @return void
  */
 public function testLinkSuccess()
 {
     $connection = ConnectionManager::get('test');
     $joint = $this->getMockBuilder('\\Cake\\ORM\\Table')->setMethods(['save'])->setConstructorArgs([['alias' => 'ArticlesTags', 'connection' => $connection]])->getMock();
     $config = ['sourceTable' => $this->article, 'targetTable' => $this->tag, 'through' => $joint, 'joinTable' => 'tags_articles'];
     $assoc = new BelongsToMany('Test', $config);
     $opts = ['markNew' => false];
     $entity = new Entity(['id' => 1], $opts);
     $tags = [new Entity(['id' => 2], $opts), new Entity(['id' => 3], $opts)];
     $saveOptions = ['foo' => 'bar'];
     $joint->expects($this->at(0))->method('save')->will($this->returnCallback(function ($e, $opts) use($entity) {
         $expected = ['article_id' => 1, 'tag_id' => 2];
         $this->assertEquals($expected, $e->toArray());
         $this->assertEquals(['foo' => 'bar'], $opts);
         $this->assertTrue($e->isNew());
         return $entity;
     }));
     $joint->expects($this->at(1))->method('save')->will($this->returnCallback(function ($e, $opts) use($entity) {
         $expected = ['article_id' => 1, 'tag_id' => 3];
         $this->assertEquals($expected, $e->toArray());
         $this->assertEquals(['foo' => 'bar'], $opts);
         $this->assertTrue($e->isNew());
         return $entity;
     }));
     $this->assertTrue($assoc->link($entity, $tags, $saveOptions));
     $this->assertSame($entity->test, $tags);
 }