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

Ram*_*min 5 php mysql json laravel eloquent

我想更新数据库中的JSON列,但出现此错误:

Array to string conversion  
Run Code Online (Sandbox Code Playgroud)

我已经array在模型中声明了列名:

protected $casts = [
    'destinations' => 'array'
];
Run Code Online (Sandbox Code Playgroud)

这是我使用的代码:

$data[] = [
    'from' => $fromArray,
    'to' => $toArray
];

Flight::where('id', $id)->update(['destinations' => $data]);
Run Code Online (Sandbox Code Playgroud)

我该怎么办 ?

Amr*_*Aly 11

您可以使用箭头访问您的 json 键,以便您可以像这样更新您的列:

Flight::where('id', $id)->update([
   'destinations->from' => $data['from'],
   'destinations->to'  => $data['to']
]);
Run Code Online (Sandbox Code Playgroud)

正如@fubar 提到的,您必须拥有mysql 5.7才能使我的解决方案起作用。

检查文档


小智 8

这段代码为我完成了工作。

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

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

$user->forceFill([
    'db_column->json_key1->json_key2' => $array_data
])->save();
Run Code Online (Sandbox Code Playgroud)


Mar*_*boc 4

根据 Github 上的对话:如果模型字段可填写,则使 json 属性可填写Taylor Otwell 建议使用以下save方法:

$model->options = ['foo' => 'bar'];

$模型->保存();

所以在你的情况下你可以这样做:

$flight = Flight::find($id); 
$flight->destinations = $data; 
$flight->save();
Run Code Online (Sandbox Code Playgroud)

  • 为什么这又被接受了?这与数据库 JSON 类型列和适当的“JSON_SET”方法无关! (7认同)