Laravel:在 Eloquent 中解码 JSON

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/30804878/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 11:47:00  来源:igfitidea点击:

Laravel: decode JSON within Eloquent

jsonlaravel

提问by be-codified

I need to JSON decode a certain column in my Eloquent query. Is there a way to do this without breaking all apart?

我需要对 Eloquent 查询中的某个列进行 JSON 解码。有没有办法做到这一点而不把所有东西分开?

So far I have this.

到目前为止,我有这个。

public function index()
{
    return Offer::all();
}

回答by ceejayoz

Use an accessoron the model:

在模型上使用访问器

public function getColumnNameAttribute($value) {
  return json_decode($value);
}

or use attribute castingto tell Laravel to do it automatically:

或者使用属性转换来告诉 Laravel 自动执行:

protected $casts = [
    'column_name' => 'array',
];

The arraycast type is particularly useful when working with columns that are stored as serialized JSON.

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

Note that you may have to stop json_encodeing your data if you use casts, as Laravel will now do that step automatically as well.

请注意,json_encode如果您使用强制转换,您可能必须停止输入数据,因为 Laravel 现在也会自动执行该步骤。