Laravel:在Eloquent中解码JSON

be-*_*ied 2 json laravel

我需要JSON解码我的Eloquent查询中的某个列.有没有办法在不分开的情况下做到这一点?

到目前为止,我有这个.

public function index()
{
    return Offer::all();
}
Run Code Online (Sandbox Code Playgroud)

cee*_*yoz 16

在模型上使用访问器:

public function getColumnNameAttribute($value) {
  return json_decode($value);
}
Run Code Online (Sandbox Code Playgroud)

或使用属性强制转换告诉Laravel自动执行此操作:

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

array在使用存储为序列化JSON的列时,强制转换类型特别有用.

请注意,json_encode如果使用演员表,您可能必须停止数据,因为Laravel现在也会自动执行该操作.