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

标签 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();
    }

}

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

enter image description here

最佳答案

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

/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();

    }

}

/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);

    }

}

/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>

关于php - 如何使用 Laravel 创建数据库驱动的多级导航菜单,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21305111/

相关文章:

php - 多个回显仅使用 1 个 SELECT *

MySQL 从两列中选择不同的名称

php - 在 Laravel Carbon 中按月执行分组时出现时区未找到错误

laravel - 在 Laravel 中处理友好 URL 的最佳实践是什么?

mysql - 如何对连接表执行查询?

mysql - 具有 DATE mysql 函数的 Laravel 查询生成器

php - MySQL 使用 PHP 将 DATETIME 更新为 NOW()

php - 将每一行用作包含的获取变量?

javascript - WordPress的function.php wp_enqueue_script不工作

python - 在 OpenShift 上安装 MySQL-python 模块