首页 > 解决方案 > 使用 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_namesub_group

$group_names = ThisIsModel::distinct()->orderBy('group_name', 'asc')->get(['group_name']);

我不知道下一步该做什么。请帮我。谢谢

标签: phplaraveleloquenttreedistinct

解决方案


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.


推荐阅读