Laravel 拉威尔散装
首先,我使用laravel中的Laravel 拉威尔散装,laravel,relationship,eloquent-relationship,Laravel,Relationship,Eloquent Relationship,首先,我使用laravel中的detach() $student = \App\StudentRegistrars::withTrashed()->findOrFail($id); $student->father_registrars()->detach(); $student->mother_registrars()->detach(); 但当我试图在拉雷维尔进行大规模分离时,我不能这样做 $students = \App\StudentRegistrar
detach()
$student = \App\StudentRegistrars::withTrashed()->findOrFail($id);
$student->father_registrars()->detach();
$student->mother_registrars()->detach();
但当我试图在拉雷维尔进行大规模分离时,我不能这样做
$students = \App\StudentRegistrars::whereIn('id', $ids);
$student->father_registrars()->detach();
$student->mother_registrars()->detach();
这个问题有什么解决方案吗?您的代码有很多问题。你很接近,但不太接近
首先,您需要知道您的变量是什么。目前,这不起作用,因为未定义$student
。您调用了变量$students
(带“s”),因此请确保使用了正确的变量
其次,在调用detach()
时,您的$students
变量是Builder
类的实例,而不是单个studentregistars
实例。您需要使用闭包完成查询
:
$students = \App\StudentRegistrars::whereIn('id', $ids)->get();
第三,detach()
您需要迭代结果并逐个调用detach()
:
foreach ($students as $student) {
$student->father_registrars()->detach();
$student->mother_registrars()->detach();
}
因此,您的最终代码将是:
$students = \App\StudentRegistrars::whereIn('id', $ids)->get();
foreach ($students as $student) {
$student->father_registrars()->detach();
$student->mother_registrars()->detach();
}
有更有效的大规模分离方法,例如直接查询和删除数据透视表中的记录:
但这个答案可以解决您的逻辑问题。当时我使用foreach,但忘记使用get()。这就是工作!谢谢你,伙计!嗨,伙计,你能回答我的另一个问题吗?
DB::table('pivot')->whereIn('column', $ids)->delete();