Laravel 仅为活跃用户选择帖子和评论

标签 laravel eloquent

我有三个模型,即用户、帖子和评论

用户表

id  username active
1   guyd        1
2   mohok       0
3   cotra       0

帖子表

id  post_content user_id
1   Hello         1
2   World         2
3   Foo           3

评论表

id post_id   user_id   commment_body
1       1       2       Great post
2       1       3       Totally disagree
3       2       1       Nice read
4       2       3       Wow
5       1       1       Thanks guys

我的帖子模型有

public function latestComments($limit = 3)
  {
    return $this->hasMany(Comment::class)
      ->where('voided', '=', 0)
      ->with('user')
      ->join('users as comment_owner', 'comments.user_id', '=', 'comment_owner.id')
      ->where('comment_owner.active', '=', 1)
      ->orderByDesc('comments.updated_at')
      ->limit($limit);
  }

我的评论模型有

public function user()
  {
    return $this->belongsTo(User::class);
  }

我只想获取 active=1 的用户的帖子和评论。我正在使用以下内容,但它给出了错误的结果。它将评论分配给没有评论的帖子。

$posts = Post::orderBy('posts.created_at', 'DESC')
      ->with('user')
      ->with('latestComments')
      ->join('users as post_owner', 'posts.user_id', '=', 'post_owner.id')
      ->where('active', 1)
      ->paginate(5);

最佳答案

您应该使用whereHas()

Post::latest()
    ->with('user', 'latestComments')
    ->whereHas('user', function ($q) {
        $q->where('active', 1);
    })
    ->paginate(5);

如果您还想过滤评论:

->with(['user', 'latestComments' => function ($q) {
    $q->whereHas('user', function ($q) {
        $q->where('active', 1);
    });
}])

关于Laravel 仅为活跃用户选择帖子和评论,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48852055/

相关文章:

mysql - 如何级联删除多态表?

php - 无法使用 Eloquent ORM 更新 mysql 行

php - Laravel Eloquent 模型 - 使用中间表获取行

php - 如何使用当前登录的用户预填 voyager BREAD 表格?

php - Laravel 将对象传递给其他方法

php - 无法加载 Eloquent 模型的关系

php - Laravel Eloquent whereDoesntHave() 文档让我感到困惑

php - fatal error 异常类 'contact' 未找到 laravel 5

css - Laravel Mix - 当本地主机上的网站不在根文件夹中时,URL 处理工作出错

php - Laravel Eloquent 关系分页