sahar_mkr's avatar

many to many relations eager load

hi everyone, I have two tables of customers and transactions, they have many to many relationships, my model and table structures written in below, I want to find the count of all customers which their transactions are in the last seven days, I wrote a query like this but it doesn't work truly, eager load does not work when I use function on with method, what should I do?

 $customers = Customer::with('transactions', function($query) use($request) {
        $query->whereBetween('created_at', lastSevenDays());
    })->count();

customer table:

-transaction_count

-phone

transactions table:

-amount

-created_at

0 likes
5 replies
MohamedTammam's avatar

You need to use whereHas

$customers = Customer::whereHas('transactions', function($query) use($request) {
        $query->where('created_at', '>=', now()->subDays(7));
    })->count();
1 like
sahar_mkr's avatar

@MohamedTammam thanks for your reply, yes, this works, actually I want to use a filter, I mean I want to put created_at as a filter and make my query according to it, but I have this error: Illuminate\Database\QueryException: SQLSTATE[23000]: Integrity constraint violation: 1052 Column 'created_at' in where clause, my query is :

$p = Customer::whereHas('transactions', function($query) use($request) {
        $query->filter($request);
    })->count();

because I have created_at in both tables transactions and customers, this doesn't accept my filter, I need this filter in my query, do you have any suggestion? thanks alot

Harsha63's avatar

@sahar_mkr Check this query

$customers = Customer::with('transactions')->all()->filter(function (Customer $customers) {
    return $customers->>where('created_at', '>=', now()->subDays(7));
});
$count = count($customers);
sahar_mkr's avatar

@Harsha63 give me the following error:

BadMethodCallException: Call to undefined method Illuminate\Database\Eloquent\Builder::all() in file C:\xampp\htdocs\analysis\vendor\laravel\framework\src\Illuminate\Support\Traits\ForwardsCalls.php on line 71

Please or to participate in this conversation.