Laravel - 检查用户是否对文章发表评论

Laravel - Check if user has commented on an article

我正在学习 Laravel,但遇到了问题。我不知道如何检查用户是否以官方方式对文章发表评论。我有 UserArticleComment 模型。

用户关系:

|_ articles() returning hasMany('Article')
|_ comments() returning morphMany('Comment')

评论关系:

|_ commentable() returning morphTo()

文章关系:

|_ user() returning belongsTo('User')
|_ comments() returning morphMany('Comment')

现在当我遍历每篇文章时,我这样做是为了检查用户是否对此发表了评论post:

@if(
    $article->comments()
    ->where('user_id', '=', $user->id)
    ->where('commentable_id', '=', $article->id)
    ->where('commentable_type', '=', 'Article')
    ->count()
    > 0
)

这样做对吗? Laravel的魔法去哪儿了?看起来很奇怪,View 也变得丑陋了。

试试这个:

@if($post->comments()->where('user_id', $user->id)->count() > 0)
@endif

你甚至可以在你的文章模型中写一个小方法:

public function hasCommentsFromUser($userId){
    return $this->comments()->where('user_id', $userId)->count() > 0;
}

用法:

@if($post->hasCommentsFromUser($user->id)
@endif

更新

你肯定要急于加载评论。这意味着不只是做

$posts = Article::all();

你做到了:

$posts = Article::with('comments')->get();

这意味着现在每个文章对象都已经加载了评论。因此,使用答案开头的代码没有意义,因为它会 运行 每篇文章的新查询。

相反,您可以使用 contains 和闭包来检查已经存在的集合:

public function hasCommentsFromUser($userId){
    return !is_null($this->comments->first(function($i, $comment) use ($userId){
        return $comment->user_id == $userId;
    }));
}