2

I am using following query for delete all corresponding data to relate on given id My code:

  public function actionDeletebyajax() 

  {
  $pid = $_POST['id'];   
  if($pid) {
        $this->findModel($pid)->delete();
        Profile::deleteAll('user_id ='.$pid);
        UserLoyalty::deleteAll('store_id ='.$pid);
        Workorderpopup::deleteAll('workorder_id ='.$pid); 
        Deal::deleteAll('workorder_id ='.$pid); 
        WorkorderCategory::deleteAll('workorder_id ='.$pid);
        store::deleteAll('owner ='.$pid);
        workorders::deleteAll('workorder_id ='.$pid); 
       echo $pid; exit;
 }
 } 

But here What i want Workorderpopup has a child table Workorderpopup_child i want delete all child record to but child table has no any relation with $pid Is there Any way to delete child's records too ?

3
  • but it has a relation with Workorderpopup. you can find and delete those then delete Workorderpopup. Commented Jul 11, 2016 at 5:55
  • 1
    define relation on cascade delete in your db Commented Jul 11, 2016 at 8:42
  • Or define triggers methods like beforeDelete() Commented Jul 11, 2016 at 12:33

1 Answer 1

3

Assuming that relation is workorderpopup_child.workorderpopup_id -> workorderpopup.id.

It could be something like this

Cascade delete by IN condition

$workorderpopups = Workorderpopup::find()
    ->select('id')
    ->where(['workorder_id' => $pid])
    ->asArray()->all();

Workorderpopup_child::deleteAll(['in', 'workorderpopup_id', array_values($workorderpopups)]);

Or like this:

Cascade delete by relation unlinking

$workorderpopups = Workorderpopup::find()
    ->select('id')
    ->where(['workorder_id' => $pid])
    ->asArray()->all();

foreach ($workorderpopups as $workorderpopup) {
    $workorderpopup->delete();
}

and then override your Workorderpopup->delete() as follows

/**
 * @inheritdoc
 */
public function delete()
{
    $this->unlinkAll('workorderpopup_child', true);        

    return parent::delete();
}

and make sure you have corresponding relation workorderpopup_child in Workorderpopup class:

/**
 * @return \yii\db\ActiveQuery
 */
public function getWorkorderpopup_child()
{
    return $this->hasMany(Workorderpopup_child::className(), ['workorderpopup_id' => 'id']);
}

p.s. i haven't tested the code above, so here can be some mistakes

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.