【发布时间】:2021-11-09 16:38:36
【问题描述】:
我有一个类别表,其中类别在同一表中提到了父项,如下面的屏幕截图所示
我想在 Laravel 中使用 Eloquent 实现自联接,其中在单独的 col 中提到了父类别:
原始 Sql 查询:
DB::select("SELECT c.id, c.name, parents.name AS `Parent Category Name`
FROM product_categories AS c
LEFT JOIN product_categories AS parents ON parents.id = c.parent
ORDER BY c.name ASC");
这给了我以下结果:
array:3 [
0 => {#1146
+"id": 1
+"name": "category 1"
+"Parent Category Name": "category 2"
}
1 => {#673
+"id": 2
+"name": "category 2"
+"Parent Category Name": null
}
2 => {#1079
+"id": 3
+"name": "category 3"
+"Parent Category Name": null
}
]
我想使用 Laravel Eloquent 达到同样的效果,然后在我的视图中循环,有人可以帮助我吗?
【问题讨论】:
-
您是否创建了包含关系和所有内容的模型...?
-
我只是使用 make: model 命令创建了模型