[英]Is there an eager "inserting" option in laravel for ManyToMany attach?
Is there a way to reduce many Insert queries to 1 when using Laravel's attach function in ManyToMany relationship?在多对多关系中使用 Laravel 的附加 function 时,有没有办法将许多插入查询减少到 1?
Here is my code:这是我的代码:
$itemIds = Item::pluck('id');
$sale = Sale::create();
foreach ($itemIds as $id) {
$sale->items()->attach($id);
}
But this way it makes as many queries as items found in the database.但是这样一来,它就可以进行与数据库中找到的项目一样多的查询。
For convenience, attach and detach also accept arrays of IDs as input.
为方便起见,附加和分离也接受 ID 的 arrays 作为输入。
For example:例如:
$user = User::find(1);
$user->roles()->attach([1, 2, 3]);
In your code, you have to use $itemIds
as array of Item Id.在您的代码中,您必须使用
$itemIds
作为项目 ID 的数组。
$itemIds = Item::pluck('id');
$sale = Sale::create();
$sale->items()->attach($itemIds);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.