在Laravel中自动删除相关行(Eloquent ORM)当我使用以下语法删除行时:$user->delete();有没有办法附加各种回调,所以它会自动执行此操作:$this->photo()->delete();最好在模型类内。
3 回答
哔哔one
TA贡献1854条经验 获得超8个赞
注意:这个答案是为Laravel 3编写的。因此,在更新版本的Laravel中可能会或可能不会很好。
您可以在实际删除用户之前删除所有相关照片。
<?phpclass User extends Eloquent{
public function photos()
{
return $this->has_many('Photo');
}
public function delete()
{
// delete all related photos
$this->photos()->delete();
// as suggested by Dirk in comment,
// it's an uglier alternative, but faster
// Photo::where("user_id", $this->id)->delete()
// delete the user
return parent::delete();
}}希望能帮助到你。
- 3 回答
- 0 关注
- 618 浏览
添加回答
举报
0/150
提交
取消
