1

I realise in Laravel 5 Eloquent there is a function called groupBy. I usually used it like so

->groupBy('rating');

Let's say in rating column, there are 3 types of ratings in integer : 1,2 and 3How do I limit it to 10 records for each kind of rating? Preferably using Eloquent but if that's not possible, I'll still accept query builder method.

John Evans Solachuk
  • 1,953
  • 5
  • 31
  • 67

2 Answers2

3

Union should work:

$type1 = Model::whereType(1)->take(10);
$type2 = Model::whereType(2)->take(10);
$type3 = Model::whereType(3)->take(10);

$types = $type1->union($type2)->union($type3)->get();
Limon Monte
  • 52,539
  • 45
  • 182
  • 213
  • 1
    Erm, isn't that like querying four times? Is it possible to just get the answers in a single query? – John Evans Solachuk Apr 15 '15 at 11:24
  • 2
    take() method will not execute the query, as far as I remember, it returns a query builder instance. Only the get() call (on the last line) will execute the query. @limonte: your link is totally different of what we are doing here. Eloquent is an ORM and the number of executed queries only depends on its implementation. – Blackus Apr 15 '15 at 11:47
1

If i'm not getting your question wrongly, your question mysql solution would be Get top n records for each group of grouped results

But when we convert our desire query to laravel, so its will look alike:

$Rating1 = Model::whereRating(1)->take(10);
$Rating2 = Model::whereRating(2)->take(10);
$Rating3 = Model::whereRating(3)->take(10);
$result = Model::unionAll($Rating1)->unionAll($Rating2)->unionAll($Rating3)->get();

And its also one query not multiple as per laravel 4.2 docs, If you still confuse to implement it, let me know.

Community
  • 1
  • 1
Safoor Safdar
  • 5,516
  • 1
  • 28
  • 32