laravel - Laravel 从一个类别及其所有子类别中获取所有帖子
问题描述
我尝试通过laravel-nestedset
拉拉维尔 8
例如:
类别型号:
public function parent()
{
$parent = $this->belongsTo('Category', 'parent_id');
return $parent;
}
public function children()
{
$children = $this->hasMany('Category', 'parent_id');
//$children->wherePublish(1);
return $children;
}
public function posts()
{
return $this->hasMany('Post');
}
我用一个例子测试了它:
category1 //with 0 post in category1
category1 > category2 //with 10 posts in category2
category1 > category2 > category3 //with 5 posts in category3
我尝试测试它:
for //category1
$category->post()->get(); // return 0 post (I want 15 posts)
for //category2
$category->post()->get(); // return 10 posts (I want 15 posts)
for //category3
$category->post()->get(); // return 5 post (I want 5 posts)
解决方案
试试这个:对于 //category1
$category->posts; // return 0 post (I want 15 posts)
对于 //category2
$category->posts; // return 10 posts (I want 15 posts)
对于 //category3
$category->posts; // return 5 post (I want 5 posts)
推荐阅读
- java - Java listIterator - 我如何让它只迭代一次?
- kotlin - Swagger 不包含 import kotlinx.serialization.Serializable 到生成的类中
- c++ - UWP 应用程序在使用应用程序包但在本地机器工作时不发送请求
- graphql - 使用 GraphQL 在 react-admin 列表组件中过滤
- java - Hibernate 从存储的函数中获取结果而不使用外键和 SerializationException
- sql - cte 表中的不同值
- c# - MVVMCross WPF:如何在视图中显示视图?
- javascript - Graphql - 如何获取所选字段的类型(字符串、整数、ID 等)
- json - 通过来自另一个 dict 的正则表达式匹配键更新值
- python - 通过并行处理将一个 csv 拆分为多个压缩 CSV 文件的有效方法