我正在使用以下查询删除所有相关数据,以便在给定的ID我的代码:
上进行关联 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;
}
}
但是这里我想要的Workorderpopup
有一个子表Workorderpopup_child
我想要删除所有子记录但是子表与$pid
没有任何关系有没有办法删除子记录呢?
答案 0 :(得分:1)
假设关系是workorderpopup_child.workorderpopup_id
- > workorderpopup.id
。
可能是这样的
按条件删除级联
$workorderpopups = Workorderpopup::find()
->select('id')
->where(['workorder_id' => $pid])
->asArray()->all();
Workorderpopup_child::deleteAll(['in', 'workorderpopup_id', array_values($workorderpopups)]);
或者像这样:
按关系取消链接级联删除
$workorderpopups = Workorderpopup::find()
->select('id')
->where(['workorder_id' => $pid])
->asArray()->all();
foreach ($workorderpopups as $workorderpopup) {
$workorderpopup->delete();
}
然后按以下方式覆盖您的Workorderpopup->delete()
/**
* @inheritdoc
*/
public function delete()
{
$this->unlinkAll('workorderpopup_child', true);
return parent::delete();
}
并确保您在workorderpopup_child
课程中有相应的关系Workorderpopup
:
/**
* @return \yii\db\ActiveQuery
*/
public function getWorkorderpopup_child()
{
return $this->hasMany(Workorderpopup_child::className(), ['workorderpopup_id' => 'id']);
}
P.S。我没有测试上面的代码,所以这里可能会出现一些错误