首页 > 解决方案 > 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)

标签: laraveleloquent

解决方案


试试这个:对于 //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)

推荐阅读