我试图从联结表中删除记录。
当frequentie
为2(每天)时,我使用联结表将planning_id's
与dagen_id's
相关联。但是当frequentie
通过示例更新为每周时,我需要从联结表中删除所有planning_id's
。
这是我到目前为止所尝试的:
public function beforeSave($insert)
{
if (parent::beforeSave($insert)) {
$this->gewijzigd_op = new \yii\db\Expression('NOW()');
$this->gewijzigd_door = Yii::$app->user->id;
if ($this->getOldAttribute('frequentie') != $this->frequentie) {
if ($this->getOldAttribute('frequentie') == 2) {
PlanningDagen::deleteAll(['planning_id' => $this->planning_id]);
}
}
return true;
} else {
return false;
}
}
使用:
$query = new \yii\db\Query();
$query->createCommand()->delete('planning_dagen', ['planning_id' => $this->planning_id)->execute();
而不是:
PlanningDagen::deleteAll(['planning_id' => $this->planning_id]);
也不起作用。
答案 0 :(得分:0)
使用afterSave
:
public function afterSave($insert, $changedAttributes) {
parent::afterSave($insert, $changedAttributes);
if (!$insert) { // since $insert is false, a database update happend instead of an insertion
if ($changedAttributes['frequentie'] == 2 && $this->frequentie != 2) { // $changedAttributes is an array which holds the attribute-values from BEFORE the update, so you can compare them with $this (active record).
PlanningDagen::deleteAll('planning_id = :id', [':id' => $this->planning_id]);
}
}
}