在 Laravel 中更新多行数据库

Update multiple rows of database in Laravel

我想要一个更新多行数据库的代码,像这样:

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;

几个小时后,我可以在 laravel 框架中得到类似这样的结果:

$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);

但是这段代码不是一个好习惯! 所以我的问题是

Is there any ORM way to do this better?!

    $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();
        }
      }
    }

并且在 Value 模型中使用 MutatorAccessor,像这样

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

这是一个简单的方法。

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

我从 this link

找到的

希望对您有所帮助。