'UpdateOrInsert in DB facade
I pass arrays with dates and places to the controller and I want to update or insert records, but if there is no data, then inserting the entire record (date, place, event) is required, but how can I specify some date or place if they are in an array and the check goes over the array and i can't know which value is not found.
DB::table('checked_seats')
->where('event_id', $event_id)
->whereIn('seat', $seat)
->whereIn('date', $dates)
->updateOrInsert(['price'=>$price]);
Solution 1:[1]
From the Laravel Docs:
Sometimes you may want to update an existing record in the database or create it if no matching record exists. In this scenario, the updateOrInsert method may be used. The updateOrInsert method accepts two arguments: an array of conditions by which to find the record, and an array of column and value pairs indicating the columns to be updated.
The updateOrInsert method will attempt to locate a matching database record using the first argument's column and value pairs. If the record exists, it will be updated with the values in the second argument. If the record can not be found, a new record will be inserted with the merged attributes of both arguments:
So you need to pass it two arrays instead of where calls.
Shortened example:
DB::table('checked_seats')
->updateOrInsert(['event_id'=>$event_id, 'seat'=>$seat], ['price'=>$price]);
This will look for an event with the specified event_id and seat. If it exists, the price will be updated. If not, a new entry with all the fields is inserted.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Thomas |
