我的数据库中的一个表列被保存为json
类型。我想在我的 Blade 模板上保存的 json 对象中显示键值,但我不确定如何。
假设我在 Newsletter
模型的表架构中有 $table->json('meta')
,meta
列具有例如{"foo": "bar"}
作为值。
我如何检索类似 $newsletter->meta->foo
的内容?因为 $newsletter->meta
在 Laravel 5.5 上默认返回字符串而不是 json 对象,需要一个简单的 json_decode
来转换它。
在每次调用时,除了 json_decode
之外,更简洁的解决方案是在该列上使用访问器,例如getMetaAttribute
但这仍然很困惑。我想要 PHP 对象检测的自动 json
列,我该如何实现?
最佳答案
您可以在模型中声明一个protected $casts
数组,您可以在其中指示 Eloquent 为 automatically convert types模型属性。在您的情况下,它看起来像这样:
/*
* @property string $meta - json is actually just a string
*/
class Newsletter extends Model {
protected $casts = [
'meta' => 'array',
];
}
// Now you can use `$meta` as array:
$newsletter = Newsletter::find(1);
$foo = array_get($newsletter->meta, 'foo');
但这仍然没有将其转换为对象。尽管文档中提到 object
是一个有效的转换类型,但我无法准确告诉您它的作用。
请注意,这些$casts
不是双向的。如果你想在 Newsletter
实例上设置 meta
,你必须创建自己的工具来将任何对象或数组转换为 json 字符串。 Eloquent 允许你定义 mutators在您的模型上完成工作。
关于php - Eloquent 集合的 json 类型列中的访问键?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46044070/