【发布时间】:2019-06-28 03:35:22
【问题描述】:
我正在尝试从我的数据库中获取“树视图”中的类别、子类别和产品。 我是 laravel 的新手,我不知道如何用雄辩的方法更好地编写这个动作。 我有 2 个表:产品和类别 每个产品都有 category_id 是类别表的外键
这是我的代码:
$categories = Category::with('products')->where('id', $category->id)->get()->toArray();
foreach ($categories as $key => $value) {
$categories[$key]['children'] = Category::with('products')->where('parent_id', $value['id'])->get()->toArray();
}
这是我的结果,很好
“结果”:[
{
"id": 2,
"name": "Root 2",
"parent_id": null,
"products": [],
"children": [
{
"id": 4,
"name": "First child of Root 2",
"parent_id": 2,
"products": [
{
"id": 5,
"category_id": 4,
"name": "مهسا واثقی",
"description": "Aut eum et rerum dolorum blanditiis et itaque ipsum. Reiciendis consectetur magni est veritatis qui. Eos veniam quo aspernatur exercitationem vel incidunt. Rem aut sunt ab exercitationem.",
"price": "58.00",
"type": "video",
"disabled": 0,
"created_at": "2019-02-03 22:38:37",
"updated_at": "2019-02-03 22:38:37"
},
]
},
{
"id": 5,
"name": "Second child of Root 2",
"parent_id": 2,
"products": []
},
{
"id": 6,
"name": "Third child of Root 2",
"parent_id": 2,
"products": []
}
]
}
],
【问题讨论】: