简体   繁体   中英

How To Bulk Update Pivot Table For Same Attributes In Laravel Many To Many

I just found out that when i'm using sync() method for updating pivot table from many to many table, it was executing multiple query.

Laravel 望远镜的截图

In my condition, i just trying to update same attributes for all related pivot table records. This is my script:

foreach ($serials as $serial) {
    $newSerials[$serial['id']] = ['warehouse_id' => 1];
} 
$record->serials()->sync($newSerials)

Are there any other solution that can do update in pivot table in only one query shot in laravel with Eloquent way?

I'm pretty sure Query Builder can handle this, but what i need to know in is Eloquent way, that maybe can combine with sync() method, because i alreay implemented sync() to the most of similar case like this in my project.

yes you can, using newPivotQuery() which make the query run directly on pivot table, you should prepare the array you want to add, give it key value pairs according to your pivot fields names, something like:

foreach ($serials as $serial) {
    $newSerials[] = 
['serials_id'=>$serial->id,'record_id'=>$record->id,'warehouse_id' => 1];
} 
$record->serials()->newPivotQuery()->insert($newSerials);

and there is another way, you can create model for the pivot table by inheriting from pivot, more details in: https://laravel.com/docs/7.x/eloquent-relationships#defining-custom-intermediate-table-models

i must note that this code insert $newSerials, not updating them, if you want to update the record, method sync() is you best choice

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM