Activerecord Yii2:在保存前/保存后从连接表中删除记录

Activerecord Yii2:在保存前/保存后从连接表中删除记录,activerecord,yii2,before-save,Activerecord,Yii2,Before Save,我正在尝试从连接表中删除记录。 当frequencie为2(每日)时,我使用连接表将planning\u id的与dagen\u id的连接起来。但是当通过示例将frequencuintieget更新为weekly时,我需要从连接表中删除所有那些planning\u id 这就是我迄今为止所尝试的: public function beforeSave($insert) { if (parent::beforeSave($insert)) { $

我正在尝试从连接表中删除记录。 当
frequencie
为2(每日)时,我使用连接表将
planning\u id的
dagen\u id的
连接起来。但是当通过示例将
frequencuintie
get更新为weekly时,我需要从连接表中删除所有那些
planning\u id

这就是我迄今为止所尝试的:

 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]);

也不起作用。

使用
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]);                       
        }
    }
}