【问题标题】:Display all approved Posts belonging to a category Laravel显示属于 Laravel 类别的所有已批准帖子
【发布时间】:2020-07-21 02:51:39
【问题描述】:

我正在尝试显示属于从 URL 传入的 slug 中的某个类别的所有已批准帖子。

我的 posts 表中有 approved 列,并且在我的控制器中完成了以下代码。

public function cats($category){
 $posts = PostCategory::where('category_slug', $category)->first()->posts;
 dd($posts);
}

上面的代码工作正常,它返回与该类别相关的所有帖子,但我试图只返回已批准的帖子,而不是全部。我该如何做到这一点?

另外,我正在尝试计算该类别中已获批准的帖子数量。 我目前有这个:{{ $category->posts->count() }}。它工作正常,但计算所有帖子。我只想返回已批准帖子的数量。

希望有人看到这一点并提供帮助。谢谢!

【问题讨论】:

  • 好吧,如果它被批准了,你如何存储?你应该看看 Laravel 的“作用域”。
  • 您在 posts 模型中有 approved 列,但这是 PostCategory 模型。希望两个模型彼此有关系。如果是这样,请发布关系,以便我们提供帮助
  • 代码在 Posts 控制器中完成。 Posts 与 Category 有 belongsTo 关系,并且 category 有很多帖子。所有这部分工作正常。我只想包含已批准的帖子,而不是返回所有帖子。

标签: laravel eloquent


【解决方案1】:

我将在 Category 模型上创建一个新关系,其中包括您的额外 where

public function approvedPosts() {
    return $this->hasMany(Post::class)->where('approved', 'true');
}

这允许您这样做:

$posts = PostCategory::where('category_slug', $category)->first()->approved_posts;

【讨论】:

  • 你摇滚!正是我想要的。非常感谢
【解决方案2】:

编辑您的类别模型帖子功能:

public function posts()
{
     $posts = Post::where('category_slug', $this->slug)->where('status', 1)->get();
     return $posts;
}

在控制器上

    $posts = PostCategory::where('category_slug', $slug)->firstorFail()->posts();
    return view('xxxxx', compact('posts'));

【讨论】:

  • “已批准”字段在帖子表上,而不是类别
  • “已批准”列在帖子表中。类别 slug 是我从路线中获得的,因此,我获取了与该 slug 相关的所有帖子(这部分工作正常)。但我只想返回批准状态设置为 true 的帖子。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-10-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多