-3

I am looking for a sql request which will provide this kind of result.

id | family       result :
 1     A          [A => 2, B => 1, C => 1]
 2     A
 3     B
 4     C

Preferably using eloquent.

Current solution :

materials()->select('family', DB::raw('count(*) as total'))
           ->groupBy('family')
           ->pluck('total', 'family');
Neok
  • 221
  • 2
  • 17
  • 1
    Have you already tried something? This is not a code-on-demand site... – Stefano Zanini May 16 '17 at 08:38
  • 1
    A simple groupBy and count query would provide you with this. – Sandeesh May 16 '17 at 08:39
  • The request I try doesn't work at all, so I don't wan't to lead people in a wrong direction – Neok May 16 '17 at 08:40
  • 1
    Don't worry, anyone with some basic SQL knowledge won't be misled by your attempts – Stefano Zanini May 16 '17 at 08:40
  • Sandeesh, no it doesn't provide the family name associate – Neok May 16 '17 at 08:40
  • I see, you get the result the way i mentioned and perform a transformation on the collection to get this result. I'll whip up a code for you if you can't get it done. – Sandeesh May 16 '17 at 08:42
  • 2
    Possible duplicate of [Laravel Eloquent groupBy() AND also return count of each group](http://stackoverflow.com/questions/18533080/laravel-eloquent-groupby-and-also-return-count-of-each-group) – Shadow May 16 '17 at 08:43
  • I will look to the [pluck](https://laravel.com/docs/5.4/collections#method-pluck) function that Guillaume use and come back – Neok May 16 '17 at 08:45
  • @Sandeesh the pluck did what I wan't, that the things I was missing. ty – Neok May 16 '17 at 08:51

2 Answers2

2

You can try something like:

$plop = Plop::selectRaw('family, COUNT(id) AS total')->groupBy('family')->pluck('total', 'family');

As you has not given enough details, it's hard to be precise.

Guillaume
  • 133
  • 6
0

With laravel eloquent, using groupBy() and count():

$model=Model::get()->groupBy('family');
foreach($model as $key => $mod)
 {
        echo $key;
        echo (count($mod));
 }
Sanzeeb Aryal
  • 4,358
  • 3
  • 20
  • 43