Yii2:如何同时从数据库中删除相关模型数据? [英] Yii2: How to simultaneously delete related models data from data base?

查看:30
本文介绍了Yii2:如何同时从数据库中删除相关模型数据?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我曾经在 Yii 上工作,现在我正在 Yii2 上构建一个新项目.

I used to work on Yii and now I'm building a new project on Yii2.

在 Yii 上有 beforeDelete() 和 afterDelete() 函数,它允许我在那里添加代码并从连接表等中删除相关行.

On Yii there was the function beforeDelete() and afterDelete() which allowed me to add the code there and delete related rows from junction tables etc..

我的问题是:在 Yii2 上,是否有另一种方法可以通过事件或数据库自身(索引上的删除事件)来做到这一点?这些程序的最佳做法是什么?

My question is: On Yii2, is there another way to do this through an event or the database its self(on delete event on indexes)? What is considered to be good practice for these procedures?

谢谢!

推荐答案

通常用外键和级联删除来处理.在这种情况下,您不必在删除事件处理程序中编写任何额外的代码.

Usually it's handled with foreign keys and cascade deletion. In this case you don't have to write any additional code in deletion event handlers.

但是,对于更复杂的情况,您可以使用相同的 ActiveRecord 事件处理程序 beforeDelete()afterDelete().删除主模型后最好在afterDelete()事件中删除相关记录.

But, for more complex situations you can use the same ActiveRecord event handlers beforeDelete() and afterDelete(). It's better to delete related records in afterDelete() event after deletion of main model.

官方文档:

这篇关于Yii2:如何同时从数据库中删除相关模型数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆