【问题标题】:Building JSON of ORM and Relationships with Laravel使用 Laravel 构建 ORM 的 JSON 和关系
【发布时间】:2014-10-30 09:54:35
【问题描述】:

实际上,我这样做是为了在控制器中构建许多 ORM 对象的 json :

Response::json(Project::all());

结果:

[
    {id: 1, name: 'test1'},
    {id: 2, name: 'test2'},
    {id: 3, name: 'test3'}
]

现在我想要:

[
    {
        id: 1, 
        name: 'test1',
        levels: [
            {
                id: 1,
                name: 'level1'
            },
            {
                id: 2,
                name: 'level2'
            }
        ]
    },
    {id: 2, name: 'test2', levels: []},
    {id: 3, name: 'test3', levels: []}
]

我的项目模型是这样的:

class Project extends Eloquent {

    protected $table = 'projects';

    public function levels()
    {
        return $this->belongsToMany('Level', 'project_has_levels');
    }

}

你是怎么做到的?

【问题讨论】:

    标签: php json laravel orm eloquent


    【解决方案1】:

    使用eager loading

    Response::json(Project::with('levels')->get());
    

    【讨论】:

      猜你喜欢
      • 2017-01-18
      • 2013-04-06
      • 2020-03-25
      • 2014-06-22
      • 1970-01-01
      • 2015-04-09
      • 2023-03-14
      • 2018-08-06
      • 1970-01-01
      相关资源
      最近更新 更多