mardi 3 août 2021

How to get prducts category wise in laravel?

Similar question was asked here

I am working on apis. My products table contain more than ten thousand products of different categories. I need to decrease query execution time so for that purpose I've to modify an api that it will fetch only 20 products of each category and group the whole api response category wise. Api response will be

{
"data": {
"products": {
  "Beauticians & Style": [
    {
      "Title": "Product A",
      "Price": "0.00",
      "DiscountPrice": 0
    },
    {
      "Title": "Product B",
      "Price": "0.00",
      "DiscountPrice": 0
    }
  ],
  "Groceries": [
    {
      "Title": "Product G",
      "Price": "0.00",
      "DiscountPrice": 0
    },
    {
      "Title": "Product R",
      "Price": "0.00",
      "DiscountPrice": 0
    },
    {
      "Title": "Product O",
      "Price": "0.00",
      "DiscountPrice": 0
    },
    {
      "Title": "Product C",
      "Price": "0.00",
      "DiscountPrice": 0
    }
  ],
  "Women's Fashion": [
    {
      "Title": "Product W",
      "Price": "0.00",
      "DiscountPrice": 0
    },
    {
      "Title": "Product O",
      "Price": "0.00",
      "DiscountPrice": 0
    },
    {
      "Title": "Product M",
      "Price": "0.00",
      "DiscountPrice": 0
    }
  ]
}
}

My Controller's code

$products= Category::whereHas('products', function($q){
                $q->take(20);
            })->get();

Category Model

class Category extends Model
{
    use HasFactory;
    public function products()
    {
        return $this->hasMany('App\Models\Product', 'CategoryID', 'CategoryID');
    }
}

I've tried this but not getting the exact resulrt. Anyone help me.



from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/37gQO3n
via IFTTT

Aucun commentaire:

Enregistrer un commentaire