Laravel 在一个json响应中获取所有相关字段

Laravel 在一个json响应中获取所有相关字段,laravel,laravel-4,Laravel,Laravel 4,我想用laravel制作一个api,我想得到如下格式的所有字段 projects: [ { id, name, logo, thumbnail, phases: [{ id, name, date, views: [{ id, name, thumbnail, images: [{ id,

我想用laravel制作一个api,我想得到如下格式的所有字段

projects: [
   {
    id,
    name,
    logo,
    thumbnail,
    phases: [{
        id,
        name,
        date,
        views: [{
        id,
        name,
        thumbnail,
        images: [{
            id,
            path: [ 5 urls for the various images ]
            date
        }]
    }]
    }]
   }
   ]
我的数据库模型如下所示 -项目有很多阶段 -阶段->有许多视图 -视图->有许多图像

模型如下所示

class Project extends \Eloquent {

// Add your validation rules here
public static $rules = [
    'title' => 'required',
];

// Don't forget to fill this array
protected $fillable = [ 'title', 'desc' ];

public function phases() {
    return $this->hasMany('Phase');
}

}


class Phase extends \Eloquent {
protected $fillable = [ 'title', 'from', 'to', 'project_id' ];

public static $rules = [
    'title' => 'required',
    'from'  => 'required',
    'to'    => 'required'
];

public function views() {
    return $this->hasMany( 'View' );
}

public function project(){
    return $this->belongsTo('Project');
}
}

class View extends \Eloquent {

// Add your validation rules here
public static $rules = [
    'title'      => 'required',
    'image_path' => 'required'
];

// Don't forget to fill this array
protected $fillable = [ 'title', 'image_path', 'caption', 'view_date', 'phase_id' ];

public function phase(){
    return $this->belongsTo('Phase');
}

}
如何获取索引响应中的所有json,我使用以下格式,但格式不同

Project::all();
您必须访问以下数据集:

Project::with('phases.views','phases.images')->get();

看起来您的模型中没有作为相关模型的图像,但是您有项目。但是您的json示例显示的是图像而不是项目,对吗?

在检索集合时,默认情况下不会加载关系(这称为延迟加载)。但是,您可以使用
with()
方法加载它们(这称为急切加载):

还可以使用点表示法链接嵌套关系:

Project:all()->with('phases.views')->get();

关于这个图像,你说得对,我最近会加上它,但是你支持这个想法
Project:all()->with('phases.views')->get();