I want a code for update multiple rows of database, somthing like this:
UPDATE values SET data='{"options":["male","female"],"default":"male"}' where project_id=1 and id=1;
UPDATE values SET data='{"options":["male","female"],"default":"male"}' where project_id=1 and id=2;
UPDATE values SET data='{"options":["male","female"],"default":"male"}' where project_id=1 and id=3;
After some hours i could get result with something like this in laravel framework:
$values = Value::where('project_id', $id)->get();
$sql = "";
foreach($request->fields as $field) {
if(!empty($field->default)) { //New default value is set
foreach($values as $value) {
$data = json_decode($value->data, true); /**data column as json object in mysql database **/
$data["default"] = $field->default;
$data = json_encode($data);
$sql .= "update ".DB::connection()->getDatabaseName().".values set data='".$data."' where id="."$value->id;";
}
}
}
DB::unprepared($sql);
but this code is not a good practice! So my question is
Is there any ORM way to do this better?!
This function is used to update the multiple records in Laravel. You just need to define what you want to update in first argument but with some unique fields, and in second argument define the which fields are unique for update and in third argument list out the fields which will actually be updated in the database.
The upsert method Laravel 8.x’s query builder comes packed with a method called upsert that will let you insert (multiple) rows that do not exist and update the rows that already exist with the new values. So, for instance, let’s say, you have a table called books and it contains the following records right now.
As the name suggest, the save () method is used to save the records. In this method, first we need to find the record and then we can add additional data into it and then we save the records. Thus, it will update the records in database.
This repository has been archived by the owner. It is now read-only. This could be a great addition for the Query Builder API. There really isn't a way to update multiple rows with different update values with the current api.
Here is an easy way to do it.
$values = Value::where('project_id', $id)->update(['data'=>$data]);
I found it from this link
Hope it helps.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With