Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

Maneet's avatar

Use Two Foreign Keys & Two Local Keys with hasMany Relation

I have four tables

Tests

id name description course_id subject_id

Course

id name description

subject

id name description

Lastly

Questions

id title option 1 option 2 option 3 option 4 course_id subject_id

I am new to laravel & I need a way to fetch all questions for a test using Eloquent Relationships.

0 likes
9 replies
CliffordAtCaveoDotNL's avatar

Maybe something like this:

class Test extends Model
{
    public function questions()
    {
        $this->hasMany(Question::class, 'course_id', 'course_id')
            ->whereColumn('questions.subject_id', '=', 'tests.subject_id');
    }
}
1 like
Maneet's avatar

I get this error Facade\Ignition\Exceptions\ViewException

SQLSTATE[42S22]: Column not found: 1054 Unknown column 'tests.subject_id' in 'where clause' (SQL: select * from questions where questions.course_id = 1 and questions.course_id is not null and questions.subject_id = tests.subject_id)

CliffordAtCaveoDotNL's avatar

In your question you said your table looked like this:

Tests |id|name|description|course_id|subject_id|

Is your table name Tests or tests?

The error says that there is no column subject_id. So either your column name is wrong or the table name?

Maneet's avatar

The Table name is tests.

& i have used the exact code which you had suggested

CliffordAtCaveoDotNL's avatar

Sorry I've overlooked something in your question but this might be the solution:

$questions = $test->course->questions()->where('subject_id', '=', $test->subject_id)->get();
Maneet's avatar

So here, is ->course a relation method?

CliffordAtCaveoDotNL's avatar

Yes, course should be a relation on your Test model:

public function course()
{
    return $this->belongsTo(Course:class, 'course_id', 'id');
}

And the course hasMany questions:

class Course extends Model
{
    public function questions()
    {
        $this->hasMany(Question::class, 'course_id', 'course_id');
    }
}

Please or to participate in this conversation.