Php laravel8:此集合实例上不存在
我想在导航栏中显示我的所有类别,并在下拉列表中显示它们的子类别 像这样: 我有一个Php laravel8:此集合实例上不存在,php,laravel,laravel-blade,Php,Laravel,Laravel Blade,我想在导航栏中显示我的所有类别,并在下拉列表中显示它们的子类别 像这样: 我有一个home.blade.php并扩展了导航刀片,还有一个HomeController 问题是我可以显示类别和子类别,但不能显示子类别的标题 当我使用foreach进行导航时,{{{$category->children}工作并显示所有子项,但当我使用它时{{{$category->children->title}}不工作并显示: 此集合实例上不存在属性[title] 此外,类别和子类别之间的关系如下: class
home.blade.php
并扩展了导航刀片,还有一个HomeController
问题是我可以显示类别和子类别,但不能显示子类别的标题
当我使用foreach进行导航时,{{{$category->children}
工作并显示所有子项,但当我使用它时{{{$category->children->title
}}不工作并显示:
此集合实例上不存在属性[title]
此外,类别和子类别之间的关系如下:
class Category extends Model
{
use HasFactory;
protected $fillable = [
'parent_id','title' , 'description', 'status',
];
public function parent()
{
return $this->belongsTo(Category::class);
}
public function children(){
return $this->hasMany(Category::class , 'parent_id');
}
}
这是我的家庭控制器:
public function index()
{
$categories = Category::with('children')
->whereNull('parent_id')
->get();
return view('home.home' , compact('categories'));
}
还有我的导航刀片:
@foreach($categories as $category)
<li class="dropdown"><a class="dropdown-toggle" data-toggle="dropdown" href="#"> {{ $category->title }} <span class="caret"></span></a>
<ul class="dropdown-menu" >
<li><a href="#">{{ $category->children->title }}</a></li>
</ul>
</li>
@endforeach
@foreach($categories作为$category)
@endforeach
正如我上面提到的,我只是在主刀片中扩展了导航
你能告诉我哪里错了吗?你需要为孩子们做另一个foreach循环来解析它们 将导航刀片更改为:
@foreach($categories as $category)
<li class="dropdown"><a class="dropdown-toggle" data-toggle="dropdown" href="#"> {{ $category->title }} <span class="caret"></span></a>
<ul class="dropdown-menu" >
@foreach($category->children as $child)
<li><a href="#">{{ $child->title }}</a></li>
@endforeach
</ul>
</li>
@endforeach
@foreach($categories作为$category)
@foreach($category->children as$child)
@endforeach
@endforeach
您需要为孩子们执行另一个foreach循环来解析它们
将导航刀片更改为:
@foreach($categories as $category)
<li class="dropdown"><a class="dropdown-toggle" data-toggle="dropdown" href="#"> {{ $category->title }} <span class="caret"></span></a>
<ul class="dropdown-menu" >
@foreach($category->children as $child)
<li><a href="#">{{ $child->title }}</a></li>
@endforeach
</ul>
</li>
@endforeach
@foreach($categories作为$category)
@foreach($category->children as$child)
@endforeach
@endforeach
非常感谢您我如何查询儿童信息?例如,我只想显示5个子类别,当我在控制器中使用take(5)
时,它限制类别$categories=Category::with(['children'=>function($q){$q->take(5);}])->whereNull('parent_id')->get()代码>非常感谢您我如何查询儿童信息?例如,我只想显示5个子类别,当我在控制器中使用take(5)
时,它限制类别$categories=Category::with(['children'=>function($q){$q->take(5);}])->whereNull('parent_id')->get()代码>