laravel删除模型时同时删除关联关系

夜阑卧听风吹雨, 铁马是你, 冰河也是你。

我们在没有在数据库中设计外键关联时想要在删除某一个模型时同时删除与改模型关联的相关数据, 可以试试下面这个方法
注意delete方法需要定义在photos方法之后;

User Model

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
<?php

class 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();
}
}

https://stackoverflow.com/questions/14174070/automatically-deleting-related-rows-in-laravel-eloquent-orm