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

cascadeDelete() public method

Clear out the data in the junction table for a given entity.
public cascadeDelete ( Cake\Datasource\EntityInterface $entity, array $options = [] ) : boolean
$entity Cake\Datasource\EntityInterface The entity that started the cascading delete.
$options array The options for the original delete.
return boolean Success.
    public function cascadeDelete(EntityInterface $entity, array $options = [])
    {
        if (!$this->dependent()) {
            return true;
        }
        $foreignKey = (array) $this->foreignKey();
        $bindingKey = (array) $this->bindingKey();
        $conditions = [];
        if (!empty($bindingKey)) {
            $conditions = array_combine($foreignKey, $entity->extract($bindingKey));
        }
        $table = $this->junction();
        $hasMany = $this->source()->association($table->alias());
        if ($this->_cascadeCallbacks) {
            foreach ($hasMany->find('all')->where($conditions)->toList() as $related) {
                $table->delete($related, $options);
            }
            return true;
        }
        $conditions = array_merge($conditions, $hasMany->conditions());
        return $table->deleteAll($conditions);
    }

Usage Example

Beispiel #1
0
 /**
  * Test cascading deletes with callbacks.
  *
  * @return void
  */
 public function testCascadeDeleteWithCallbacks()
 {
     $articleTag = TableRegistry::get('ArticlesTags');
     $config = ['sourceTable' => $this->article, 'targetTable' => $this->tag, 'cascadeCallbacks' => true];
     $association = new BelongsToMany('Tag', $config);
     $association->junction($articleTag);
     $this->article->association($articleTag->alias());
     $counter = $this->getMockBuilder('StdClass')->setMethods(['__invoke'])->getMock();
     $counter->expects($this->exactly(2))->method('__invoke');
     $articleTag->eventManager()->on('Model.beforeDelete', $counter);
     $this->assertEquals(2, $articleTag->find()->where(['article_id' => 1])->count());
     $entity = new Entity(['id' => 1, 'name' => 'PHP']);
     $association->cascadeDelete($entity);
     $this->assertEquals(0, $articleTag->find()->where(['article_id' => 1])->count());
 }
All Usage Examples Of Cake\ORM\Association\BelongsToMany::cascadeDelete