mardi 24 juillet 2018

How to limit my query to get only 5 products per category?

Alright, hello guys, I'm struggling for a while with this problem so I will need your help.

So here is the problem I have database with more than 6000 products and I wanted to get some specific categories and their sub categories and only the products associated with them.

Here is a sample array that I have made that stores the categories (the key is the chosen category ID and the array value is all of the sub categories ID's).

  $products_categories = array(
        3 => [
            4, 5 , 6
        ],
        10 => [
            40, 30, 20
        ]
    );

And that's my eloquent query to get all of the products with those categories.

  $all_fetched_categories = array_merge(...$products_categories);

  if (!empty($products_categories)) {
        $products = Product::query();

        $products = $products->with([
            'media',

        ])
        ->active()
        ->top()
        ->whereHas('categories', function ($query) use ($all_fetched_categories) {
                $query->whereIn('shop_category_id', $all_fetched_categories);
            });

        $products = $products->get();
    }

So the question is, I will need only 5 products per main category. With the code that I provided I can't make logical limitation in the query.



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire