Laravel Bulk Detach

ぐ巨炮叔叔 提交于 2021-01-29 04:41:33

问题


First, I use detach() in laravel with this approach and this is work!

$student = \App\StudentRegistrars::withTrashed()->findOrFail($id);
$student->father_registrars()->detach();
$student->mother_registrars()->detach();  

But when I am trying to mass detach in laravel, I can't do that.

$students = \App\StudentRegistrars::whereIn('id', $ids);
$student->father_registrars()->detach();
$student->mother_registrars()->detach(); 

Any solution about this problem?


回答1:


There's quite a few issues with your code. You're close, but not quite there.

First, you need to be aware of what your variable is. Currently, this is not working, as $student is not defined. You called your variable $students (with an 's'), so make sure you're using the right variable.

Secondly, at the point you're calling detach(), your $students variable is an instance of the Builder class, not a single StudentRegistrars instance. You need to finalize your query with a closure:

$students = \App\StudentRegistrars::whereIn('id', $ids)->get();

Thirdly, the detach() method only works on a single instance, so if you called $students->father_registrars()->detach(), it would still fail.

You need to iterate your results and call detach() one-by-one:

foreach ($students as $student) {
  $student->father_registrars()->detach();
  $student->mother_registrars()->detach(); 
}

You final code would therefore be:

$students = \App\StudentRegistrars::whereIn('id', $ids)->get();
foreach ($students as $student) {
  $student->father_registrars()->detach();
  $student->mother_registrars()->detach(); 
}

There are more efficient approaches to mass detachment, such as directly querying and deleting records from the pivot table (or tables):

DB::table('pivot')->whereIn('column', $ids)->delete();

But this answer serves to fix your logic issues.



来源:https://stackoverflow.com/questions/62599520/laravel-bulk-detach

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!