Laravel eloquent 不更新 JSON 列:数组到字符串的转换
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/45361861/
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
Laravel eloquent does not update JSON column : Array to string conversion
提问by Ramin
I want to update a JSONcolumn in my database but I get this error :
我想更新数据库中的JSON列,但出现此错误:
Array to string conversion
I have declared the column name as array
in the model :
我已经array
在模型中声明了列名:
protected $casts = [
'destinations' => 'array'
];
this is the code that I use :
这是我使用的代码:
$data[] = [
'from' => $fromArray,
'to' => $toArray
];
Flight::where('id', $id)->update(['destinations' => $data]);
What should I do ?
我该怎么办 ?
采纳答案by Maraboc
According to this conversation on Github : Make json attributes fillable if Model field is fillableTaylor Otwell recommande the use of save
method :
根据 Github 上的这个对话:如果模型字段可填充,则使 json 属性可填充Taylor Otwell 建议使用save
方法:
$model->options = ['foo' => 'bar'];
$model->save();
$model->options = ['foo' => 'bar'];
$model->save();
So in you case you can do it like this :
所以在你的情况下,你可以这样做:
$flight = Flight::find($id);
$flight->destinations = $data;
$flight->save();
回答by Amr Aly
You can access your json keys using the arrow so you can update your column like so:
您可以使用箭头访问您的 json 键,以便您可以像这样更新您的列:
Flight::where('id', $id)->update([
'destinations->from' => $data['from'],
'destinations->to' => $data['to']
]);
As @fubar mentioned you have to have mysql 5.7in order to have my solution to work.
正如@fubar 提到的,您必须拥有mysql 5.7才能使我的解决方案起作用。
check the docs
检查文档
回答by fubar
You're getting that error because you're trying to update your model using the Query Builder, which basically just creates raw SQL queries. It isn't aware of any data casting, etc defined within your model. You therefore have three choices:
您收到该错误是因为您尝试使用查询构建器更新模型,该构建器基本上只是创建原始 SQL 查询。它不知道您的模型中定义了任何数据转换等。因此,您有三个选择:
1) Find your model, and run the update on your model instance.
1) 找到您的模型,并在您的模型实例上运行更新。
$flight = Flight::findOrFail($id);
$flight->update(['destinations' => $data]);
2) Convert the data to a string before updating.
2) 更新前将数据转换为字符串。
$data = json_encode($data);
Flight::where('id', $id)->update(['destinations' => $data]);
3) Use a database that supports JSON column queries, per @AmrAly's suggestion. Beware of this option, as not all databases support JSON columns.
3) 根据@AmrAly 的建议,使用支持 JSON 列查询的数据库。请注意此选项,因为并非所有数据库都支持 JSON 列。