18

How can I group by relation?

Example

Sales::with('product_detail.product')->groupBy('product_name')->get()

How can I get a result with eloquent code?

Xedecimal
  • 3,153
  • 1
  • 19
  • 22
yudijohn
  • 1,248
  • 3
  • 19
  • 43

5 Answers5

19

You can specify a callback function for grouping your relation like this:

Sales::with(['product_detail.product' => function($query){
        $query->groupBy('product_name');
    }])->get();
Michiel
  • 150
  • 1
  • 6
Imtiaz Pabel
  • 5,307
  • 1
  • 19
  • 24
  • 4
    Since the relationship is pulled in with a separate query and not a join, this does not do what OP was asking for. – miken32 Dec 02 '21 at 20:07
10

I think the top answer is not answering the question. As I understand, the aim is to group the results of the outer query, not the relationship.

This is not possible in an Eloquent-y DB call because the call for the With is separate. You can manually join the tables and group by the required column.

If you want to stay Eloquent-y, there are many convenient methods available to Collections, including GroupBy. So you can get the data first and group later.

Sahil Dawka
  • 101
  • 1
  • 2
  • 2
    Hey Sahil, any chance you could supply a line of code or example that may be useful to the asked question? – Aaron Feb 17 '20 at 14:34
3

This may already be old but yeah, it can help a seeker.

You can chain directly to relationships/distant relationships with groupBy in Laravel. I don't know if this is specific to any version but V8 works. And the relationship is loaded as well like you would use with.

 Sales::query()->where('this', $that)->get()->groupBy('product.name'); // OR

 Sales::query()->where('this', $that)->get()->groupBy('product.status.name');
Lekia
  • 105
  • 1
  • 12
0

laravel >= 7 you can use:

In controller

$user->sales()->groupBy('product_name')->get();

In User.php file :

public function sales(){
     return $this->hasMany('App\Sales','user_id');
}
-3

Group by distant relation:

Sales::select(DB::raw('count(*) as count'), 'products.name')
  ->join('product_details', 'sales.product_detail_id', '=', 'product_details.id')
  ->join('products', 'product_details.product_id', '=', 'products.id')
  ->groupBy('products.name')
  ->get();
Artur Anyszek
  • 489
  • 5
  • 6