【发布时间】:2021-10-08 13:32:15
【问题描述】:
here 提出了类似的问题。
我正在研究 API。我的产品表包含一万多个不同类别的产品。我需要减少查询执行时间,因此为此,我必须修改一个 API,该 API 将仅获取每个类别的 20 个产品,并将整个 API 响应按类别分组。 API 响应如下所示。
{
"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
}
]
}
}
控制器
$products = Category::with('products', function($q){
$q->take(20);
})->get();
类别模型
class Category extends Model
{
use HasFactory;
public function products()
{
return $this->hasMany('App\Models\Product', 'CategoryID', 'CategoryID');
}
}
我试过了,但没有得到确切的结果。
【问题讨论】: