Q:

How to delete data using join in yii2

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 ?

A:

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

