Php 显示主类别下的子类别和项目数
我是拉威尔的新手,在构建“真实世界”项目的同时,我也在努力学习 我的项目是分类网站。目前,我在步骤中,我应该显示所有类别,子类别和每个子类别下的项目数量 在数据库中,我描述了名为Php 显示主类别下的子类别和项目数,php,laravel,laravel-5.2,Php,Laravel,Laravel 5.2,我是拉威尔的新手,在构建“真实世界”项目的同时,我也在努力学习 我的项目是分类网站。目前,我在步骤中,我应该显示所有类别,子类别和每个子类别下的项目数量 在数据库中,我描述了名为categories的表中的所有类别(主类别和子类别)。有一个名为parent\u id的列,它是父类别(如果是子类别)的id 在modelCategory.php中,我有 public function item() { return $this->hasMany('Item','category_id'
categories
的表中的所有类别(主类别和子类别)。有一个名为parent\u id
的列,它是父类别(如果是子类别)的id
在modelCategory.php
中,我有
public function item()
{
return $this->hasMany('Item','category_id');
}
public function children()
{
return $this->hasMany('App\Category', 'parent_id');
}
public function getCategories()
{
$categoires = Category::where('parent_id',0)->get();
$categoires = $this->addRelation($categoires);
return $categoires;
}
public function selectChild( $id )
{
$categoires = Category::where('parent_id',$id)->get();
$categoires = $this->addRelation($categoires);
return $categoires;
}
public function addRelation( $categoires )
{
$categoires->map(function( $item, $key)
{
$sub = $this->selectChild($item->id);
$item->itemCount = $this->getItemCount($item->id , $item->parent_id );
return $item = array_add($item, 'subCategory', $sub);
});
return $categoires;
}
public function getItemCount( $category_id, $parent_id )
{
if( $parent_id == 0)
{ // for root-caregory
$ids = Category::select('id')->where('parent_id', $category_id)->get();
$array = array();
foreach ($ids as $id)
{
$array[] = $id->id;
}
return Item::whereIn('category_id', $array )->count();
}
else
{
return Item::where('category_id', $category_id)->count();
}
}
在我的控制器中
public function index()
{
$Category = new Category;
$allCategories = $Category->getCategories();
return view('frontend.home', compact('allCategories'));
}
在视图中,这就是我显示父类别的方式
@foreach($allCategories as $cats)
<li><a href="#">{{ $cats->title }}</a>/li>
@endforeach
错误是
未定义的属性:Illumb\Database\Eloquent\Collection::$title
当我
{dd($allCategories)}
我看到它们在数组中。您的子关系将返回一个集合,而不是一个模型,因此您还必须循环子对象:
@foreach($allCategories as $cats)
<li><a href="#">{{ $cats->title }}</a>
<ul class="sub-category">
@if($cats->children)
@foreach($cats->children as $child)
<li><a href="#"> {{ $child->title }} </a></li>
@endforeach
@endif
</ul>
</li>
@endforeach
@foreach($cats形式的所有类别)
@如果($cats->children)
@foreach($cats->childrenas$child)
@endforeach
@恩迪夫
@endforeach
哦,我知道我错过了什么。非常感谢你的帮助!
@foreach($allCategories as $cats)
<li><a href="#">{{ $cats->title }}</a>
<ul class="sub-category">
@if($cats->children)
@foreach($cats->children as $child)
<li><a href="#"> {{ $child->title }} </a></li>
@endforeach
@endif
</ul>
</li>
@endforeach