dtny30176 2017-02-02 19:49
浏览 56

在laravel中从数据库创建,排序菜单和子菜单

I'm trying to build menu section which is being fetched from the database, I've menus and sub menus too. I've mentioned a column with the name parent_id if NULL represents it is a parent element if any id is present it is submenu of that particular id of menu element. following is my table

/***************** Menu Elements Table ****************/
|id |   name     |   link    | parent_id | sort_id |
____________________________________________________
|1  | Home       | home      |    NULL   |   NULL  |
|2  | About Us   | about-us  |    NULL   |   NULL  |
|3  | Services   | services  |     2     |     2   |
|4  | Vision     | vision    |     2     |     1   |
|5  | Contact us | contact-us|    NULL   |   NULL  |

and menu to be in format something like this:

<ul id="main-nav">
    <li class="menu-item"><a href="index">Home</a></li>
    <li class="menu-item"><a href="about-us">About Us</a>
        <ul class="sub-nav">
            <li><a href="vision">Vision</a></li>
            <li><a href="services">Services</a></li>
    </li>
    <li class="menu-item"><a href="contact-us">Contact us</a></li>
</ul>

Menu is also sorted according to the sort_id

Till now I'm able to sort the menu elements but I want the sort to be parent_id specific.

$menu_elements = MenuElements::orderBy('sort_id', 'asc')->get()->all();

I'm bit confused how to achieve this. Help me out.

Thanks

  • 写回答

1条回答 默认 最新

  • 普通网友 2017-02-02 19:56
    关注

    You can just add another orderBy():

    $menu_elements = MenuElements::orderBy('parent_id', 'asc')->orderBy('sort_id', 'asc')->get()->all();
    

    UPDATE

    To do this in the view I would just change your query to:

    $menu_elements = MenuElements::all();
    

    Then in your view:

    <ul id="main-nav">
        @foreach($menu_elements->where('parent_id', null) as $parent_item)
            <li class="menu-item">
                <a href="{{ $parent_item->link }}">{{ $parent_item->name }}</a>
                @php
                    $children = $menu_elements->where('parent_id', $parent_item->id);
                @endphp
                @if(!$children->isEmpty())
                    <ul class="sub-nav">
                        @foreach($children->sortBy('sort_id') as $child)
                            <li><a href="{{ $child->link }}">{{ $child->name }}</a></li>
                        @endforeach
                    </ul>
                @endif
            </li>
        @endforeach
    </ul>
    
    评论

报告相同问题?

悬赏问题

  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 关于大棚监测的pcb板设计
  • ¥15 stm32开发clion时遇到的编译问题
  • ¥15 lna设计 源简并电感型共源放大器