【问题标题】:Laravel get all posts from a category and all it's sub-categoriesLaravel 从一个类别及其所有子类别中获取所有帖子
【发布时间】:2021-12-20 18:07:39
【问题描述】:

我尝试通过 laravel-nestedset 来实现它

Laravel 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)

【问题讨论】:

    标签: laravel eloquent


    【解决方案1】:

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

    【讨论】:

      【解决方案2】:

      可以使用自定义查询加载祖先和后代,例如:

      $category_id = 5;
      $categories  = Category::descendantsAndSelf($category_id)
                       ->pluck('id')
                       ->toArray();
      
      $posts = Post::whereIn('category_id', $categories)->get();
      

      我解释了逻辑,但您可以在模型上创建本地范围。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2011-09-26
        • 1970-01-01
        • 2020-06-05
        • 1970-01-01
        • 1970-01-01
        • 2017-10-14
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多