0

i have a query that i want to take some certain amount of object from each category for example 4 from category 1 and 4 from category 2 and here is what i wrote :

$wish = DB::table('table')
            ->where('category_id', $category)
            ->whereIn('type_id',[2,4])
            ->take(8)->get();

so here i want to say to take 4 from type_id 2 and get another 4 from type_id 4 . is there any way to do that or any package to do that in caravel eloquent ??

Farshad
  • 1,830
  • 6
  • 38
  • 70
  • Separate queries for a particular category. I dont see how it can split the query to just take some from this category and some from this other category – Chris Medina May 19 '20 at 10:39
  • i think you just have to make 2 queries. `groupBy` will not help you here – Flame May 19 '20 at 10:40
  • https://stackoverflow.com/questions/16720525/how-to-select-top-3-values-from-each-group-in-a-table-with-sql-which-have-duplic – Chris Medina May 19 '20 at 10:42

1 Answers1

0

Give this a try

$wishesByType = DB::table('table')
    ->where('category_id', $category)
    ->whereIn('type_id', [2, 4])
    ->get()
    ->groupBy('type_id');

$wishes = $wishesByType->map(function ($wish) {
    return $wish->take(8)->all();
})->all();

This is not an optimized solution because you are fetching all records and then limiting by each type. Still if you okay with this then this is a quick solution.

Digvijay
  • 7,836
  • 3
  • 32
  • 53