雄辩:hasnot with参数



我有以下雄辩的模型:

用户 |id

POST |id

注释 |id |post_id |user_id

使用雄辩,我如何获取特定用户尚未评论的所有帖子?

我已经尝试了:

在模型

public function noCommentOf(User $user) {
    $this->hasNot('AppComment')->commentOf($user);
}

模型注释

public function commentOf($query, User $user) {
    return $query->where('user_id', '=', $user->id);
}

我这样做的方式是通过查询具有whereDoesnthave关系的Post模型。在您的控制器中:

public function getPostsWithoutCommenter(){
  $userId = 1; // Could be `$user`, `use($user)` and `$user->id`.
  $posts = AppPost::whereDoesntHave("comments", function($subQuery) use($userId){
    $subQuery->where("user_id", "=", $userId);
  })->get();
}

这将假定commentsPost模型上定义为:

public function comments(){
  return $this->hasMany(Comment::class);
}

基本上,如果comments$userId的支票的关系返回Collection,则将从结果集中忽略。

邮政模型

public function comments()
{
    return $this->hasMany(Comment::class)
}

然后获取帖子

$posts = Post:: whereDoesntHave('comments', function ($query) use ($userId) {
    $query->where('user_id', $userId);
});

获得没有评论的帖子

$posts = Post::has('comments', '=', 0)->get();

我认为:

$user->post()->leftJoin('comments', 'posts.id', '=', 'comments.post_id')->whereNull('comments.id');

为了获取特定用户未对使用Laravel雄辩的ORM评论的所有帖子,您可以将whereDoesntHave()方法与查询约束结合使用。

首先,定义模型中的以下关系:

class User extends Model
{
    public function comments()
    {
        return $this->hasMany(Comment::class);
    }
}
class Post extends Model
{
    public function comments()
    {
        return $this->hasMany(Comment::class);
    }
}

接下来,在您的帖子模型中,定义了一个称为noCommentOf()的范围,该范围接受用户实例作为参数:

public function scopeNoCommentOf($query, User $user)
{
    $query->whereDoesntHave('comments', function ($query) use ($user) {
        $query->where('user_id', $user->id);
    });
}

现在,您可以使用此范围获取特定用户未评论的所有帖子:

$user = User::find($userId);
$posts = Post::noCommentOf($user)->get();

最新更新