Laravel批量分离 [英] Laravel Bulk Detach

查看:84
本文介绍了Laravel批量分离的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

首先,我通过这种方法在laravel中使用 detach(),这是可行的!

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();  

但是当我试图在laravel中大规模分离时,我无法做到这一点.

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?

推荐答案

您的代码有很多问题.您已经接近了,但还没到那儿.

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

首先,您需要了解变量是什么.当前,此操作不起作用,因为未定义 $ student .您调用了变量 $ students (带有's'),因此请确保您使用的变量正确.

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.

第二,在您调用 detach()时,您的 $ students 变量是 Builder 类的实例,而不是一个 StudentRegistrars 实例.您需要使用 closure :

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();

第三, detach()方法仅适用于单个实例,因此,如果您调用 $ students-> father_registrars()-> detach(),它仍然会失败.

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

您需要迭代结果,然后一个接一个地调用 detach():

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.

这篇关于Laravel批量分离的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆