Yii 删除有关系的活动记录 [英] Yii delete active records with relationship

查看:28
本文介绍了Yii 删除有关系的活动记录的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两张桌子:

users{
id
username
password
}

person{
id
fname
lname
user_id
}

和用户模型中的关系:

public function relations()
{
    // NOTE: you may need to adjust the relation name and the related
    // class name for the relations automatically generated below.
    return array(
        'person'=>array(self::HAS_ONE, 'Person', 'user_id'),
    );
}

在教程中说我可以通过在用户控制器中写入来删除它们:

In tutorial there was said I can delete both by writting in user controller:

$this->loadModel($id)->person->delete();

但它只删除数据库中的个人记录.

but it deletes only person record in db.

如果我写:

$this->loadModel($id)->with('person')->delete();

这只会删除数据库中的用户记录.

This deletes only user record in db.

如何使用这些关系或更改它们来删除它们?

How can I delete both using these relations or changing them perhaps?

当然我可以写成 3 行:

Of course I could write that in 3 lines:

$user=$this->loadModel($id);
Person::model()->findByPk($user->person_id)->delete();
$user->delete();

它会删除两者.

推荐答案

Yii 没有实现自动处理子关系上的 DB 写操作的逻辑.因此,如何实现目标取决于您.有不同的方式:

Yii has no logic implemented to automatically handle DB write operations on child relations. So its up to you how to achieve your target. There are different ways:

  1. 使用您的数据库并在外键列上定义一个 ON DELETE CASCADE 约束.不需要额外的 Yii 逻辑.

  1. Use your DB and define a ON DELETE CASCADE constraint on the foreign key column. No additional Yii logic is required.

覆盖beforeDelete() beforeSave() afterDelete() afterSave()CActiveRecord 或使用事件系统(参见 wiki)在您的模型中实现您的逻辑.

Overwrite the beforeDelete() beforeSave() afterDelete() afterSave() functions of CActiveRecord or use the event system (see wiki) to implement your logic inside your model.

使用您的控制器并手动完成工作.

Use your controller and do the work manually.

我总是使用第一种方式 (1.) 并实现 DB 约束.但有时在删除一条 DB 记录之前需要处理一些逻辑.那么我会选择第二种方式(2.),也许结合第一种方式.

I would always use the first way (1.) and implement DB constraints. But sometimes it is necessary to process some logic before delete a DB record. Then I would choose the second way (2.) maybe in combination with the first one.

在您的控制器中实现所有逻辑 (3.) 并不是一种真正好的代码风格,除非您确定项目的其他部分不需要实现的代码.

To implement all the logic inside your controller (3.) isn't really a good code style except you are sure that the implemented code isn't needed at another part of your project.

这篇关于Yii 删除有关系的活动记录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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