[英]Laravel eloquent does not update JSON column : Array to string conversion
我想更新数据库中的JSON列,但出现此错误:
Array to string conversion
我已在模型中将列名称声明为array
:
protected $casts = [
'destinations' => 'array'
];
这是我使用的代码:
$data[] = [
'from' => $fromArray,
'to' => $toArray
];
Flight::where('id', $id)->update(['destinations' => $data]);
我应该怎么办?
这段代码为我完成了工作。
$user = User::where('id', $request->user_id)
->first();
$array_data = ["json_key3"=>"value"];
$user->forceFill([
'db_column->json_key1->json_key2' => $array_data
])->save();
您收到该错误是因为您正在尝试使用查询生成器更新您的模型,它基本上只是创建原始 SQL 查询。 它不知道您的模型中定义的任何数据转换等。 因此,您有以下三种选择:
1) 找到您的模型,并在您的模型实例上运行更新。
$flight = Flight::findOrFail($id);
$flight->update(['destinations' => $data]);
2) 在更新之前将数据转换为字符串。
$data = json_encode($data);
Flight::where('id', $id)->update(['destinations' => $data]);
3) 根据@AmrAly 的建议,使用支持 JSON 列查询的数据库。 请注意此选项,因为并非所有数据库都支持 JSON 列。
根据 Github 上的对话: Make json attributes fillable if Model field is fillable Taylor Otwell recommande the use of save
method:
$model->options = ['foo' => 'bar'];
$模型->保存();
所以在你的情况下你可以这样做:
$flight = Flight::find($id);
$flight->destinations = $data;
$flight->save();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.