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

    public function unlink(EntityInterface $sourceEntity, array $targetEntities, $options = [])
    {
        if (is_bool($options)) {
            $options = ['cleanProperty' => $options];
        } else {
            $options += ['cleanProperty' => true];
        }
        $this->_checkPersistenceStatus($sourceEntity, $targetEntities);
        $property = $this->property();
        $this->junction()->connection()->transactional(function () use($sourceEntity, $targetEntities, $options) {
            $links = $this->_collectJointEntities($sourceEntity, $targetEntities);
            foreach ($links as $entity) {
                $this->_junctionTable->delete($entity, $options);
            }
        });
        $existing = $sourceEntity->get($property) ?: [];
        if (!$options['cleanProperty'] || empty($existing)) {
            return true;
        }
        $storage = new SplObjectStorage();
        foreach ($targetEntities as $e) {
            $storage->attach($e);
        }
        foreach ($existing as $k => $e) {
            if ($storage->contains($e)) {
                unset($existing[$k]);
            }
        }
        $sourceEntity->set($property, array_values($existing));
        $sourceEntity->dirty($property, false);
        return true;
    }

Usage Example

示例#1
0
 /**
  * Test liking entities having a non persited target entity
  *
  * @expectedException \InvalidArgumentException
  * @expectedExceptionMessage Cannot link not persisted entities
  * @return void
  */
 public function testUnlinkWithNotPersistedTarget()
 {
     $config = ['sourceTable' => $this->article, 'targetTable' => $this->tag, 'joinTable' => 'tags_articles'];
     $assoc = new BelongsToMany('Test', $config);
     $entity = new Entity(['id' => 1], ['markNew' => false]);
     $tags = [new Entity(['id' => 2]), new Entity(['id' => 3])];
     $assoc->unlink($entity, $tags);
 }
All Usage Examples Of Cake\ORM\Association\BelongsToMany::unlink