Updating multiple rows of a database in Laravel

I need code to update multiple rows of a database, something 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 a few hours, I can get the result with something like this in the 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 good practice! So my question is:

Is there any way ORM can do it better ?!

+4
source share
2 answers

Here is an easy way to do this.

$values = Value::where('project_id', $id)->update(['data'=>$data]);

I found it from this link

Hope this helps.

+6
source
    $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) {      
          $tmp=$value->data;
          $tmp->default = $field->default;
          $value->data = $tmp;
          $value->save();
        }
      }
    }

And in the model Valueuse Mutatorand Accessorlike this

public function getDataAttribute($value)
{
    return json_decode($value);
}
public function setDataAttribute($value)
{
    $this->attributes['data'] = json_encode($value);
}

. http://laravel.com/docs/4.2/eloquent#accessors-and-mutators

- https://yadi.sk/i/BnC3HYozehoy2

-4

All Articles