A similar question was asked here.
I am working on APIs. My products table contains 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 will fetch only 20 products of each category and group the whole API response category-wise. The API response will be like the following.
{
"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
}
]
}
}
Controller
$products = Category::with('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 result.