Chaaarles's avatar

Updating multiple pivot rows at once

I have two tables connected with a many-to-many relationship, products and stores. I would like to update the availability of many products in many stores at the same time.

Is this possible with Eloquent, or would i have to use raw SQL?

0 likes
4 replies
Chingy's avatar
Chingy
Best Answer
Level 6

Upsert probably. First argument is an array of arrays, that each array contain the same keys, different values. Second argument is an an array of strings that accepts the aforementioned keys that should be used to uniquely identify records. Third argument accepts which column should be updated.

If record not found with the unique combination of the 2nd argument, it creates a record, otherwise update existing one

1 like
Chaaarles's avatar

@Chingy Thank you! I'll try that 😀

edit: worked like a charm!

1 like
Chingy's avatar

@Chaaarles Caution with upsert. If you have race conditions, aka have many attempts to write on the same records simultaneously, you will run into Deadlock issues. Don't over spam it. Upsert is fast, but locks the records during the updating process. The more they are, the longer they are locked.

1 like

Please or to participate in this conversation.