xiankai
xiankai

Reputation: 2781

CakePHP - deleting data by associated key

I have a few tables that are joined through a distant relationship - for example:

A.id = B.a_id, B.id = C.b_id, C.id = D.c_id

And given A.id, I want to delete all the rows in D that are associated with A.id.

Since Model::deleteAll() does not accept any joins, only conditions, how do I go about it?

All the models (A, B, C, D) already have belongTo relationships defined.

My last resort would be raw SQL, but I would like to know if there's a way in CakePHP to do it.

I could not find similar questions as they all were about deleting ALL the associated data, rather than just one table's data via an associated key.

Upvotes: 1

Views: 306

Answers (1)

Salines
Salines

Reputation: 5767

Use Containable behavior to find D records

public function deleteD($idA){
$this->ModelA->Behaviors->load('Containable');

$options = array(
    'contain' => array(
       'ModelB' => array(
           'ModelC' = array(
               'ModelD'
           )
       )
    ),
    'conditions' => array('ModelA' => $idA)
);
$findDIds = $this->ModelA->find('all',$options);
debug($findDIds); // find right path to ModelD
$ids = Hash::extract($findDIds,'{n}.ModelD.id');
$this->loadModel('ModelD');
   foreach($ids as $id){
       $this->ModelD->delete($id);
   }
}

Note, I not tested this function.

Upvotes: 1

Related Questions