首页 > 解决方案 > Laravel 5.6 Eloquent Relations 2 级

问题描述

如何获取这张图片上的所有数据。

如何获取这张图片上的所有数据。我使用 Laravel 5.6 Eloquent 模型。

标签: phplaravel

解决方案


Keep the columns being named as what you wrote in the relation chart, and name the tables as years, depts, candidates, then define Year hasMany Dept, and hasMany Candidate:

class Year extends Model
{    
    public function depts()
    {
        return $this->hasMany('App\Dept');
    }

    public function candidates()
    {
        return $this->hasMany('App\Candidate');
    }
}

Then you can take them all by with method, in Controller:

$years = App\Year::with(['depts', 'candidates'])->get();

UPDATE

Candidate can also be the main model by applying Nested Eager Loading.

make sure you've defined Candidate and Dept first:

Candidate Model

class Candidate extends Model
{    
    public function Year()
    {
        return $this->belongsTo('App\Year');
    }
}

Dept Model

class Dept extends Model
{    
    public function Year()
    {
        return $this->belongsTo('App\Year');
    }
}

In Controller

$candidates = App\Candidate::with('year.depts')->get();

推荐阅读