Laravel Counting Related Models with date I have list of users and showing how many Product they have.
User::withCount('products')->orderBy('products_count')->get()
I want add show product count with specific date period , tried this but not works
User::withCount('products')
->whereBetween('buy_date', array('2021-05-19 00:00:00', '2021-05-19 23:59:59'))
->orderBy('products_count')
->get()
Is buy_date on products table?
So why are you trying to filter that on users table?!
I want show User with product count with time period . for ex. how many product user have last month
Have you ever opened the documentation?
Because the answer is there...
give link and I will check
can you help find where I have error?
$users = User::withCount([
'products' => function ($query) {
$query->whereBetween('buy_date', ['2021-06-19 00:00:00', '2021-07-19 23:59:59']);
}])
->orderBy('products_count', 'desc')
->get();
Try following:
\App\Models\User::query()
->withCount([
'products' => function (\Illuminate\Database\Eloquent\Builder $query) {
$query->whereBetween('buy_date', ['2021-05-19 00:00:00', '2021-05-19 23:59:59']);
}
])
->orderBy('products_count')
->get();
how can i use it in function, it not works like this
public function statistics()
{
$users = \App\Models\User::query()
->withCount([
'products' => function (\Illuminate\Database\Eloquent\Builder $query) {
$query->whereBetween('buy_date', ['2021-05-19 00:00:00', '2021-05-19 23:59:59']);
}
])
->orderBy('products_count')
->get();
return view('statistics', ['users'=>$users ]);
}
$users = User::withCount([
'products' => function ($query) {
$query->whereBetween('buy_date', ['2021-05-25 00:00:00', '2021-05-25 23:59:59']);
}])
->orderBy('products_count', 'desc')
->get();
,
@foreach($users as $user)
<tr>
<td>{{$user->name}}</td>
</tr>
@endforeach
when I using foreach it showing first result from this date 2021-05-25 00:00:00', '2021-05-25 23:59:59 and after this showing all results.
It must show only whereBetween date , but showing all user
Try adding ->having('products_count').
It showing no result
$users = User::withCount([
'products' => function ($query) {
$query->whereBetween('buy_date', ['2021-05-25 00:00:00', '2021-05-25 23:59:59']);
}])
->having('products_count')
->orderBy('products_count', 'desc')
->get();
forks like this ->having('products_count', '>' , 0)
Please sign in or create an account to participate in this conversation.