我想要一个代码来更新多行数据库,如下所示:
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);
但这段代码不是一个好习惯! 所以我的问题是
有更好的ORM方式可以做到这一点吗?!
答案 0 :(得分:8)
这是一种简单的方法。
$values = Value::where('project_id', $id)->update(['data'=>$data]);
我是从this链接
找到的希望它有所帮助。
答案 1 :(得分:-4)
$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
模型中使用Mutator
和Accessor
,就像这样
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