2017-07-27 41 views
3

我想在我的数据库更新JSON列,但我得到这个错误:Laravel雄辩不更新JSON柱:数组字符串转换

Array to string conversion 

我已经宣布了列名作为array型号:

protected $casts = [ 
    'destinations' => 'array' 
]; 

这是我使用的代码:

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

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

我该怎么办?

+1

试试这个:'$ =飞行飞行::发现($ ID); $ flight-> destinations = $ data; $ flight-> save();'see [here](https://github.com/laravel/framework/pull/15464) – Maraboc

+0

@Maraboc发布您的答案请 – Ramin

回答

0

根据在Github此对话:Make json attributes fillable if Model field is fillable泰勒Otwell recommande使用save方法:

$模型 - >选项= [ '富'=> '酒吧'];

$ model-> save();

所以你如果你能做到这一点是这样的:

$flight = Flight::find($id); 
$flight->destinations = $data; 
$flight->save(); 
1

您可以用箭头,你可以像这样更新栏访问您的JSON键:

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

正如@fubar提到的,你必须有mysql 5.7才能有我的解决办法工作。

检查docs

+0

这不是所有数据库都支持的。例如,MySQL 5.7+。 – fubar

+1

@farar谢谢我更新了我的回答 –

2

因为你想更新使用查询生成器,它基本上仅仅是创建原始的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列。

+0

我知道这可以使用'json_encode'来完成,但我想使用雄辩的投射特征。感谢你的回答 – Ramin