Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/laravel/10.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Laravel 拉威尔散装_Laravel_Relationship_Eloquent Relationship - Fatal编程技术网

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

首先,我使用laravel中的
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();