如何使菜单和子菜单动态Laravel

wnvonmuf  于 2023-01-10  发布在  其他
关注(0)|答案(2)|浏览(138)

我想使菜单和子菜单动态。我用它们的链接制作了菜单,但无法制作子菜单,请帮助我制作数据库结构
表格名称:menu

id              menu_name       url                timestamps

表格:sub_menu

id      submenu_name       link      menu_id  timestamps

我的查询是这样的

public function menu()
{   
   $sql=\DB::table('menu')->rightjoin('sub_menu','menu.id','=','sub_menu.menu_id')
   ->select('submenu_name','link','url','menu_id','menu_name','menu.id')->get();
    return view('products.show.menu',compact('sql'));
}

视图

<ul>    
    @foreach($sql as $key => $nav)
      @if($key > 0)
        <li>
            <a href="#">{{$nav->menu_name}}</a>
             @if (count($nav->submenu_name) > 0 )
                <ul>        
                 @foreach($nav->submenu_name as $child)
                    <li><a href="#">{{$child->submenu_name}}</a></li>
                @endforeach
                @endif
                </ul>
        </li>
      @endif
    @endforeach
    </ul>
w46czmvw

w46czmvw1#

是否已为这些表设置模型?查询将为每个菜单/子菜单组合返回多行,这意味着您不能按原样对其进行迭代。此处无需使用查询生成器。
假设您的模型设置如下(您需要检查关系中使用的名称空间):

class Menu extends Eloquent
{
    protected $table = 'menu';

    public function submenu()
    {
        return $this->hasMany('App\SubMenu');
    }
}

class SubMenu extends Eloquent
{
    protected $table = 'sub_menu';

    public function menu()
    {
        return $this->belongsTo('App\Menu');
    }
}

在控制器中,您可以执行以下操作:

public function menu()
{
    $menu = Menu::with('submenu')->get();

    return view('products.show.menu', compact('menu'));
}

那么在你看来:

<ul>
    @foreach($menu as $menuItem)
        <li>
            {{ $menuItem->menu_name }}
            @if( ! $menuItem->submenu->isEmpty())
                <ul>
                    @foreach($menuItem->submenu as $subMenuItem)
                        <li>{{ $subMenuItem->submenu_name }}</li>
                    @endforeach
                </ul>
            @endif
        </li>
    @endforeach
</ul>
3b6akqbq

3b6akqbq2#

你可以不用控制器

`@foreach(App\Menu::get() as $menuItem)
  @if( ! $menuItem->submenu->isEmpty() )
    <li class="dropdown">
    <a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-expanded="false">
        {{ $menuItem->menu_name }}
    </a>
  @else
    <li>
    <a href="{{ $menuItem->url }}">{{ $menuItem->menu_name }}</a>
  @endif

  @if( ! $menuItem->submenu->isEmpty())
      <ul class="dropdown-menu" role="menu">
          @foreach($menuItem->submenu as $subMenuItem)
              <li><a href="{{ $subMenuItem->link }}">{{ $subMenuItem->submenu_name }}</a></li>
          @endforeach
      </ul>
  @endif
  </li>
@endforeach`

相关问题