Search code examples
laravellaravel-5foreign-keysrelational-databaseeloquent-relationship

How can i Get Laravel relationship with its relationship values?


I have a laravel database design where every result has belongsToMany relationship with question and every question has belogsTo relationship with subject. i want to fetch subject names from results with single statement on laravel

I have tried this https://laravel.com/docs/5.6/eloquent-relationships#has-many-through from laravel documentation

here is my code from Result model

public function questions(){
    return $this->belongsToMany('App\questions', 'results_questions', 'result_id', 'questions_id');
}

the code from question model

public function subject(){
    return $this->belongsTo('App\Subject','subject_id');
}

and this is what I tried from documentation (doesn't work)

public function subjects(){
    return $this->hasManyThrough(
        'App\Subject',
        'App\Questions',
        'subject_id', // Foreign key on question table...
        'questions_id', // Foreign key on result table...
        'id', // Local key on question table...
        'id' // Local key on result table...
    );
}

Solution

  • Try to remove 5th and 6th parameters from your relation, since they are optional. Also, should your Questions model be lowercase?

    public function subjects(){
        return $this->hasManyThrough(
            'App\Subject',
            'App\questions', //*Should this be lowercase?*
            'subject_id', // Foreign key on question table...
            'questions_id', // Foreign key on result table...
        );
    }