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

时间:2015-01-24 13:44:03

标签: php laravel laravel-4

我正在学习Laravel并遇到问题。我不知道如何检查用户是否以官方方式评论了一篇文章。我有UserArticleComment型号。

用户关系:

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

评论关系:

|_ commentable() returning morphTo()

文章关系:

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

现在当我在每篇文章上进行迭代时,我这样做是为了检查用户是否评论了这篇文章:

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

这是正确的方法吗? Laravel的神奇之处在哪里?它看起来很奇怪,而且视图变得丑陋。

1 个答案:

答案 0 :(得分:2)

试试这个:

@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;
    }));
}
相关问题