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

时光毁灭记忆、已成空白 提交于 2021-01-21 07:18:49

问题


I want to update a JSON column in my database but I get this error :

Array to string conversion  

I have declared the column name as array in the model :

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 ?


回答1:


According to this conversation on Github : Make json attributes fillable if Model field is fillable Taylor Otwell recommande the use of save method :

$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();



回答2:


You can access your json keys using the arrow so you can update your column like so:

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.

check the docs




回答3:


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:

1) Find your model, and run the update on your model instance.

$flight = Flight::findOrFail($id);
$flight->update(['destinations' => $data]);

2) Convert the data to a string before updating.

$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.




回答4:


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();


来源:https://stackoverflow.com/questions/45361861/laravel-eloquent-does-not-update-json-column-array-to-string-conversion

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!