首先,我detach()
在laravel中使用这种方法,这是可行的!
$student = \App\StudentRegistrars::withTrashed()->findOrFail($id);
$student->father_registrars()->detach();
$student->mother_registrars()->detach();
但是,当我试图在laravel中大规模分离时,我无法做到这一点。
$students = \App\StudentRegistrars::whereIn('id', $ids);
$student->father_registrars()->detach();
$student->mother_registrars()->detach();
关于这个问题有什么解决方案吗?
您的代码有很多问题。您已经接近,但还没到那儿。
首先,您需要了解变量是什么。目前,这是行不通的,$student
未定义。您调用了变量$students
(带有“ s”),因此请确保使用正确的变量。
其次,在您要调用的时候detach()
,您的$students
变量是Builder
该类的一个实例,而不是单个StudentRegistrars
实例。您需要使用来结束查询closure
:
$students = \App\StudentRegistrars::whereIn('id', $ids)->get();
第三,该detach()
方法仅适用于单个实例,因此,如果调用$students->father_registrars()->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();
}
有更有效的方法来进行大规模分离,例如直接查询数据表或从数据透视表中删除记录:
DB::table('pivot')->whereIn('column', $ids)->delete();
但这答案可以解决您的逻辑问题。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句