Yii2:在之前/之后保存连接表中的记录

时间:2016-02-01 17:19:15

标签: activerecord yii2 before-save

我试图从联结表中删除记录。 当frequentie为2(每天)时,我使用联结表将planning_id'sdagen_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]);

也不起作用。

1 个答案:

答案 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]);                       
        }
    }
}