Make a BelongsToMany Relation with Third Model?

Posted 2 years ago by selmonal

How Can i make this relation? I have tables like below

students
    id
batches
    id
enrollments
    student_id
    batch_id
fees
    id
    batch_id

batches and students are have a belongsToMany relation ship. Now i want to make a relation fees with students? How can i make it? I've tested below but it doesn't work

public function students()
{
    return $this->belongsToMany(Student::class, 'enrollments', 'batch_id', 'student_id');
}

it's running this query.

select *, (select count(*) from `students` inner join `enrollments` on `students`.`id` = `enrollments`.`student_id` where `enrollments`.`batch_id` = `fees`.`id` and `confirmed_at` is not null) as `students_count` from `fees` limit 1

select `students`.*, `enrollments`.`batch_id` as `pivot_batch_id`, `enrollments`.`student_id` as `pivot_student_id` from `students` inner join `enrollments` on `students`.`id` = `enrollments`.`student_id` where `enrollments`.`batch_id` = '1' and `confirmed_at` is not null

as i see enrollments.batch_id matches with fees.id. It should matches with fees.batch_id as i expect.

Is it possible? or am i doing wrong? Thanks

Please sign in or create an account to participate in this conversation.

Reply to

Use Markdown with GitHub-flavored code blocks.