簡體   English   中英

Yii2 afterDelete將不會被調用

[英]Yii2 afterDelete won't get called

我的應用程序中有用戶頁面。當我在用戶屏幕中刪除用戶時,同樣的用戶記錄也要在其他表中刪除。我完成了createCommand。但是函數本身不會被調用。 UserController和用戶模型。

控制器:

public function actionDelete($id)
{
    $user=$this->findModel($id)->delete();  
    return $this->redirect(['index']);
}

模型:

public function afterDelete()
    {
    //print"<script>alert('delete')</script>";
        $id = $this->id;
        parent::afterDelete();
        $connection     = Yii::$app->getDb();
        $tshirtaccessTable  = TshirtAccess::tableName();
        $userRoleTable      = UserRole::tableName();

        $transaction    = $connection->beginTransaction();
        try {
            $sql1 = "DELETE FROM ".$tshirtaccessTable." WHERE userid=:userid";
            $sql2 = "DELETE FROM ".$userRoleTable." WHERE userid=:userid";

            $connection->createCommand($sql1)->bindValue(':userid',$id)->execute();
            $connection->createCommand($sql2)->bindValue(':userid',$id)->execute();

            $transaction->commit();
        } catch (\Exception $e) {
            $transaction->rollBack();
            //throw $e;
        }
    }

由於您正在直接執行SQL查詢以執行刪除操作,因此未調用afterDelete。 而您已經在模型中編寫了afterDelete。

為了完成這項工作,您需要找到並刪除模型的對象。

$model = TshirtAccess::find()->where(['userid' => $user_id])->one(); //all()
$model->delete(); // this will trigger your afterDelete function and execute your code.

這樣可以解決您的問題。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM