How to create a database-driven multi-level navigation menu using Laravel(如何使用 Laravel 创建数据库驱动的多级导航菜单)
问题描述
我是 Laravel 4 的新手,我对它的模型完全感到困惑.我正在尝试为我的项目创建一个数据库驱动的导航菜单,我所知道的是我必须创建一个模型来与数据库交互(基于我从 codeigniter 获得的知识).我一直在学习,我厌倦了无法前进,这是我到现在想出的代码:
I'm new to Laravel 4 and I'm totally confused about it's models. I'm trying to create a database-driven navigation menu for my project and all I know is I have to create a model to interact with the database (based on my knowledge from codeigniter). I have been studying alot and I'm tired of not being able to go forward, this is the code I have come up with till now:
/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();
}
}
这是我将用于此模型的导航数据库表:
And this is my Navigation database table I will use for this Model:
推荐答案
所以在从不同来源进行更多搜索和阅读之后,这就是我想出的,并且运行良好:
So after doing much more searching and reading from different sources this is what I came up with and it's working fine:
/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>
这篇关于如何使用 Laravel 创建数据库驱动的多级导航菜单的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何使用 Laravel 创建数据库驱动的多级导航菜单
基础教程推荐
- 在多维数组中查找最大值 2021-01-01
- Libpuzzle 索引数百万张图片? 2022-01-01
- 超薄框架REST服务两次获得输出 2022-01-01
- 在 Woocommerce 中根据运输方式和付款方式添加费用 2021-01-01
- 在 PHP 中强制下载文件 - 在 Joomla 框架内 2022-01-01
- 如何在 PHP 中的请求之间持久化对象 2022-01-01
- 通过 PHP SoapClient 请求发送原始 XML 2021-01-01
- mysqli_insert_id 是否有可能在高流量应用程序中返回 2021-01-01
- XAMPP 服务器不加载 CSS 文件 2022-01-01
- WooCommerce 中选定产品类别的自定义产品价格后缀 2021-01-01