MUHAMMAD Siyab
MUHAMMAD Siyab

Reputation: 446

How to deal with the following query using Eloquent in Laravel

I'm working on a School Management System in Laravel 5.7. I have two tables.

  1. students
  2. monthly_fees

What i want is to select the months with value 1 by joining the monthly_fees table with students and by giving a condition on students table. To make it simple. I wanna do the following query in Eloquent way.

SELECT * FROM `students` 
INNER JOIN `monthly_fees` ON `monthly_fees`.`student_id` = `students`.`id` 
WHERE `students`.`class` = 'whatever'

Upvotes: 1

Views: 83

Answers (3)

Chris Kelker
Chris Kelker

Reputation: 571

Why do a join at all. With Laravel you can simply eager-load and filter the results by the relationship table (The eloquent way):

Students::whereHas('MonthlyFees', function ($query) {
     $query->where('months', 1);
})->get();

By doing this you would only get the Student results where the months column is equal to 1. Then simply filter through the results in a blade view as you normally would. Hope this helps!

Upvotes: 2

George Hanson
George Hanson

Reputation: 3030

The Eloquent way would be to do something like the following:

Student::with('monthly_fees')->where('class', 'whatever')->get();

That will return all Students belonging to that class with their monthly fees. You'll obviously need to make sure you have setup the correct relationships on your Student and MonthlyFee models.

Upvotes: 0

Iftikhar uddin
Iftikhar uddin

Reputation: 3182

Can you try the below query:

DB::select(`students.*`, `monthly_fees.*`)
    ->from(`students`)
    ->join(`monthly_fees`, function($join) {
        $join->on(`monthly_fees.student_id`, `=`, `students.id`);
    })
    ->where(`students.class`, `=`, 'whatever')
    ->get();

Upvotes: 0

Related Questions