php - 使用 eloquent 列出树视图
问题描述
我在下面有这个表结构
表视图
+------+---------------+---------------+---------------+
|id | group_name | sub_group | title |
+------+---------------+---------------+---------------+
|1 | Mobile Phone | Apple | Iphone X |
|2 | Mobile Phone | Apple | Iphone 7 Plus|
|3 | Mobile Phone | Samsung | J6 Plus |
|4 | Mobile Phone | Nokia | XpressMusic |
+------+---------------+---------------+---------------+
如何循环这个表并存储在一个数组中,看起来像这样
环形
Mobile Phone
-> Apple
-> Iphone X
-> Iphone 7 Plus
-> Samsung
-> J6 Plus
-> Nokia
-> XpressMusic
这是我使用 eloquent 的代码,我在 group_name sub_group 下运行了一个不同的代码,但我不知道如何根据group_name
和sub_group
$group_names = ThisIsModel::distinct()->orderBy('group_name', 'asc')->get(['group_name']);
我不知道下一步该做什么。请帮我。谢谢
解决方案
Normally you cannot have that easily without having 03 separates table and using eloquent relations like here.
But for you case with single table, maybe this works ?
ThisIsModel::select(DB::raw("group_concat(distinct(group_name)) as group_name, group_concat(distinct(sub_group)) as sub_group, group_concat(title) as title"))->groupBy('sub_group', 'group_name')->get()->groupBy('group_name')->toArray();
which gives result as follow:
[
"Mobile Phone" => [
[
"group_name" => "Mobile Phone",
"sub_group" => "Apple",
"title" => "Iphone X,Iphone 7 Plus",
],
[
"group_name" => "Mobile Phone",
"sub_group" => "Nokia",
"title" => "XpressMusic",
],
[
"group_name" => "Mobile Phone",
"sub_group" => "Samsung",
"title" => "J6 Plus",
],
],
]
To get the leaves on title
, you just need to explode with ,
separator and you have all in one query.
推荐阅读
- ios - 无法合成具有不完整类型“void”的属性“testjj”
- javascript - 顶级sequelize v5的where子句错误
- python - Python:重塑数据框并使用预定义的行重新组合特定列中的数据
- c++ - Visual Studio Code 在预期文件夹之外创建可执行文件
- intellij-idea - IntellijJ IDEA 2020.2.3 未启动
- c++ - 在 C++ 中的链表中添加新节点时程序崩溃
- scala - 将列表或变量动态传递到 Scala 中 spark databricks 笔记本中的 SQL 单元的正确方法是什么?
- r - 使用ggplot将geom_label定位在网络外部?
- python - 如何交换给定字符串中的字符?
- c# - 如何使用 json 正文发送 POST 请求?(RestSharp C#)