Laravel 5.6 Eloquent Relations level 2

How to get all of the data on this picture.

How to get all of the data on this picture. Im using Laravel 5.6 Eloquent Model.

2 answers

  • answered 2018-11-08 06:33 Mou Hsiao

    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();
    

  • answered 2018-11-08 06:43 Emtiaz Zahid

    You should first understand the relations with laravel model.

    i tried to map the relation. let me know if i am wrong.

    here i think:

    • a candidate have one year
    • one year have multiple candidate
    • one year belongs to one department (this part confusing)

    Department Model

    class Department extends Model
    {
        public function years(){
            return $this->hasMany(Year::class,'dept_id');
        }
    }
    

    Year Model:

    class Year extends Model
    {
        public function department(){
            return $this->belongsTo(Department::class,'dept_id');
        }
    
        public function candidates(){
            return $this->hasMany(Candidate::class,'year_id', 'year_id');
        }
    }
    

    Candidate Model:

    class Candidate extends Model
    {
        public function year(){
            return $this->belongsTo(Year::class,'year_id','year_id');
        }
    }
    

    Controller:

     public function index()
        {
            $data = Year::with(['department', 'candidate'])->get();
            dd($data);
        }