【问题标题】:Return Nested Json from database as an array with Laravel使用 Laravel 从数据库中返回嵌套的 Json 作为数组
【发布时间】:2020-09-24 22:05:07
【问题描述】:

我的数据库中有这个嵌套的 json

 {

"skills":{
    "skill1":{
        "description":"deal 100 damage",
        "cost":2,
        "name":"basic skill"
    },
        "skill2":{
        "description":"deal 900 damage",
        "cost":1,
        "name":"special skill"
    }
}
}

但是当我从我的数据库中获取这个 json 时,它会返回一个字符串 (image1)

我使用 laravel 从数据库中获取数据。

 public function list(){
        $data = Cd::all();
        return $data;  
  }

我希望这个 json 像邮递员预览(image2)中一样,一个数组,所以我可以访问它的属性,

示例:在 foreach 之后,我可以访问“skill1->description”、cost 等。

我该怎么做?

【问题讨论】:

    标签: arrays json laravel multidimensional-array


    【解决方案1】:

    在您的 Cd 模型中,您应该投射您的“技能”属性:

    class Cd extends Model 
    {
     protected $casts = ['skills'=>'array'];
    .... 
    }
    

    通过使用 '$casts',您的模型会自动将 json 字段转换为字符串而不是纯字符串

    有关数组和 json 转换的更多信息:

    https://laravel.com/docs/7.x/eloquent-mutators#array-and-json-casting

    【讨论】:

    • 会尝试!,我应该这样做后迁移吗?
    • 不,此代码无需迁移即可获得想要的结果
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-04-13
    • 2019-12-03
    • 2016-11-22
    • 1970-01-01
    • 1970-01-01
    • 2019-12-04
    • 1970-01-01
    相关资源
    最近更新 更多