【问题标题】:How to store JSON in mysql laravel如何在 mysql laravel 中存储 JSON
【发布时间】:2018-03-26 04:50:51
【问题描述】:

所以,我正在尝试将数据作为 JSON 存储在数据库中,我已经看到内置通知表这样做了。

我创建了一个“文本”类型的字段并存储了这个(示例)

{"filenames":["D0BmpFOdyUp4YyA8tqpL60VxO9kXsfciP9eLhIxd.jpeg","nAAs1xeErQSxPGxPvP68bCMn4a0E3y4EcgwfCwJl.png"],"title":"asdasdasa","content":"adasdasa"}

它按预期返回字符串,我如何让它理解为一个数组?

我必须在模型中添加一些东西还是...?

谢谢。

【问题讨论】:

    标签: php mysql json laravel


    【解决方案1】:

    请参阅 Laravel 文档中的 attribute Casting。在 Eloquent 模型类中,添加 $casts 属性,例如:

    /**
     * The attributes that should be cast to native types.
     *
     * @var array
     */
    protected $casts = [
        'your_column_name' => 'array'
    ];
    

    来自 Laravel 文档:

    模型上的$casts 属性提供了一种将属性转换为常见数据类型的便捷方法。 $casts 属性应该是一个数组,其中键是要转换的属性的名称,值是您希望将列转换为的类型。

    【讨论】:

    • 谢谢!我已经找了好几个小时了。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-11-22
    • 2012-05-06
    • 2018-05-14
    • 1970-01-01
    • 1970-01-01
    • 2016-04-29
    • 1970-01-01
    相关资源
    最近更新 更多