简体   繁体   English

Laravel Eloquent 不更新 JSON 列:数组到字符串的转换

[英]Laravel eloquent does not update JSON column : Array to string conversion

I want to update a JSON column 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?我应该怎么办?

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.7 in order to have my solution to work.正如@fubar 提到的那样,您必须拥有mysql 5.7才能使我的解决方案正常工作。

check the docs检查文档

This code did the work for me.这段代码为我完成了工作。

$user = User::where('id', $request->user_id)
        ->first();

$array_data = ["json_key3"=>"value"];

$user->forceFill([
    'db_column->json_key1->json_key2' => $array_data
])->save();

You're getting that error because you're trying to update your model using the Query Builder, which basically just creates raw SQL queries.您收到该错误是因为您正在尝试使用查询生成器更新您的模型,它基本上只是创建原始 SQL 查询。 It isn't aware of any data casting, etc defined within your model.它不知道您的模型中定义的任何数据转换等。 You therefore have three choices:因此,您有以下三种选择:

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. 3) 根据@AmrAly 的建议,使用支持 JSON 列查询的数据库。 Beware of this option, as not all databases support JSON columns.请注意此选项,因为并非所有数据库都支持 JSON 列。

According to this conversation on Github: Make json attributes fillable if Model field is fillable Taylor Otwell recommande the use of save method:根据 Github 上的对话: Make json attributes fillable if Model field is fillable Taylor Otwell recommande the use of save method:

$model->options = ['foo' => 'bar']; $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();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM