在 Laravel 中更新多行数据库

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/28539400/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 10:56:36  来源:igfitidea点击:

Update multiple rows of database in Laravel

phplaravellaravel-4orm

提问by Hamid Zamani

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:

几个小时后,我可以在 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);

but this code is not a good practice! So my question is

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

Is there any ORM way to do this better?!

有没有什么 ORM 方法可以做得更好?!

回答by Vishal Tarkar

Here is an easy way to do it.

这是一个简单的方法。

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

I found it from thislink

我是从这个链接找到的

Hope it helps.

希望能帮助到你。

回答by vitalik_74

    $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 Valuemodel use Mutatorand Accessor, like this

Value模型中使用Mutatorand Accessor,像这样

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

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

请参阅文档http://laravel.com/docs/4.2/eloquent#accessors-and-mutators

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

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