Home > Enterprise >  Laravel distinct() function is not working along get() function
Laravel distinct() function is not working along get() function

Time:06-23

When I write this

$customers_id = Order::where('user_id', $id)->pluck('id');
$customers = OrderItem::whereIn('order_id',$customers_id)->distinct('product_id')->count();

it give me correct answer of 2 but when I use get instead of count It gives me all values

CodePudding user response:

I Think this gona going to be the distinct() count

$customers = OrderItem::whereIn('order_id',$customers_id)->distinct()->count('producr_id);

CodePudding user response:

Distinct doesn't take arguments: https://laravel.com/docs/9.x/queries#select-statements

Your goal is to get the total count distinct by product_id only. You have to specify the columns/fields you want to distinct using the select method:

$customers_id = Order::where('user_id', $id)->pluck('id');
$customers = OrderItem::select('product_id')->whereIn('order_id',$customers_id)->distinct()->count();
  • Related