laravel路由中的类别树
我正在做一个产品目录与雄辩,我有2个模型:产品和类别。每个类别可以有多个产品,每个产品属于一个类别。我的类别模型有以下列:laravel路由中的类别树,laravel,laravel-4,laravel-routing,Laravel,Laravel 4,Laravel Routing,我正在做一个产品目录与雄辩,我有2个模型:产品和类别。每个类别可以有多个产品,每个产品属于一个类别。我的类别模型有以下列: id title parent_id slug 产品型号有: id title body category_id slug 当我创建一个类别时,默认情况下parent_id设置为0,这意味着它不是子类别,而是父类别,即: Cars --Audi 汽车的父项id设置为0,奥迪的父项id设置为1(因为汽车类别的id为1)。然后,我为嵌套行创建了模型: ItemsHelpe
id
title
parent_id
slug
产品型号有:
id
title
body
category_id
slug
当我创建一个类别时,默认情况下parent_id设置为0,这意味着它不是子类别,而是父类别,即:
Cars
--Audi
汽车的父项id设置为0,奥迪的父项id设置为1(因为汽车类别的id为1)。然后,我为嵌套行创建了模型:
ItemsHelper.php:
<?php
class ItemsHelper {
private $items;
public function __construct($items) {
$this->items = $items;
}
public function htmlList() {
return $this->htmlFromArray($this->itemArray());
}
private function itemArray() {
$result = array();
foreach($this->items as $item) {
if ($item->parent_id == 0) {
$result[$item->title] = $this->itemWithChildren($item);
}
}
return $result;
}
private function childrenOf($item) {
$result = array();
foreach($this->items as $i) {
if ($i->parent_id == $item->id) {
$result[] = $i;
}
}
return $result;
}
private function itemWithChildren($item) {
$result = array();
$children = $this->childrenOf($item);
foreach ($children as $child) {
$result[$child->title] = $this->itemWithChildren($child);
}
return $result;
}
private function htmlFromArray($array) {
$html = '';
foreach($array as $k => $v) {
$html .= "<ul>";
$html .= "<li>" . $k . "</li>";
if(count($v) > 0) {
$html .= $this->htmlFromArray($v);
}
$html .= "</ul>";
}
return $html;
}
}
它输出一个类别树。我可以通过访问/category/cars
访问汽车类别,但如果它是汽车类别的子类别,那么它应该是/category/cars/audi
,我如何在路线中设置它
routes.php:
Route::resource('category', 'CategoryController');
您需要手动添加另一个路由,指向
CategoryController
中的方法,或者指向另一个控制器或闭包。标准资源控制器不会创建任何能够处理/category/cars/audi
语法的路线。我建议使用NULL
而不是0
来表示缺少父级
。如果我手动创建/category/{cat1}/{cat2},它最多会更深两层,我可以有10层,ie:/类别/汽车/奥迪/a8
Route::resource('category', 'CategoryController');