PPK
PPK

Reputation: 51

I am trying to get records from two tables with laravel using WhereAs

I am trying to get records of users from two tables..SALES TABLE & USER TABLE.

But from the SALES table, i want to get only sales of the current month for each of the user.

I have merged the tables already from the model, but when i try to get the record using this code it keeps pulling the sales for both current month and previous month from SALES table..

$myrecords = User::whereHas('sales', function($query) {
              $query->whereMonth('sales.created_at', Carbon::now()->month); 
}) 
->get();

Please what am i doing wrong here

Upvotes: 1

Views: 239

Answers (1)

Kurt Friars
Kurt Friars

Reputation: 3764

$users = User::whereHas('sales', function($query) {
    $query->whereMonth('sales.created_at', Carbon::now()->month);  
})->get();

This will get all users who had sales last month, so if you try to say ->with('sales'), it will get all users who had sales last month, and all other sales they ever had.

If you are looking to limit the relation, you need to do the following.

User::with(['sales' => function ($query) {
    $query->whereMonth('created_at', Carbon::now()->month);  
}])->get();

That will give you all users with only sales that occurred this month.

Upvotes: 2

Related Questions