如何使用Laravel创建数据库驱动的多级导航菜单

Hos*_*ari 10 php mysql laravel laravel-4

我是Laravel 4的新手,我对它的模型完全感到困惑.我正在尝试为我的项目创建一个数据库驱动的导航菜单,我所知道的是我必须创建一个与数据库交互的模型(基于我在codeigniter中的知识).我一直在研究很多,我已经厌倦了无法前进,这是我迄今为止提出的代码:

/app/models/navigation.php

<?php

class Navigation extends Eloquent {

    /**
     * The database table used by the model.
     *
     * @var string
     */
    protected $table = 'navigation';

    /**
     * Get the unique identifier for the menu item.
     *
     * @return mixed
     */
    public function getItemIdentifier()
    {
        return $this->getKey();
    }

}
Run Code Online (Sandbox Code Playgroud)

这是我将用于此模型的导航数据库表:

在此输入图像描述

Hos*_*ari 28

因此,在进行了更多搜索和从不同来源阅读之后,这就是我想出来的并且工作正常:

/app/models/Navigation.php

<?php

class Navigation extends Eloquent {

    /**
     * The database table used by the model.
     *
     * @var string
     */
    protected $table = 'navigation';

    public function parent() {

        return $this->hasOne('navigation', 'id', 'parent_id');

    }

    public function children() {

        return $this->hasMany('navigation', 'parent_id', 'id');

    }  

    public static function tree() {

        return static::with(implode('.', array_fill(0, 4, 'children')))->where('parent_id', '=', NULL)->get();

    }

}
Run Code Online (Sandbox Code Playgroud)

/app/controllers/HomeController.php

<?php

class HomeController extends BaseController {

    protected $layout = "layouts.main";

    public function showWelcome()
    {

        $items = Navigation::tree();

        $this->layout->content = View::make('layouts.home.index')->withItems($items);

    }

}
Run Code Online (Sandbox Code Playgroud)

/app/views/layouts/home/index.blade.php

<ul>
    @foreach($items as $item)
        <li>{{ $item->title }}
            @foreach($item['children'] as $child)
            <li>{{ $child->title }}</li>
            @endforeach
        </li>
    @endforeach
</ul>
Run Code Online (Sandbox Code Playgroud)

  • 不,你可以继续无限级别 (2认同)