如何删除带有枢轴的记录(Laravel 5)

时间:2016-02-05 12:49:02

标签: laravel-5

例如,如果我有表:

project

user_project

我想删除项目表中的一些项目以及与该项目相关的user_project表中的所有记录,我该怎么做? 我能用单线做吗?因为我不希望某个项目被删除但在user_project中仍然存在...

1 个答案:

答案 0 :(得分:0)

如果您在迁移中设置删除级联,删除项目表中的记录将自动从相关表中删除记录,否则您必须手动删除它。

// to delete records from both table, let first delete from the 
// child table then after that we delete from the parent table.
$project = Project::find($id);

// let assume you have define the user relation in your model and 
// its a many to many association
$project->users()->detach();
$project->delete();