我正在学习Laravel并遇到了问题。我不知道如何检查用户是否以官方方式对文章发表了评论。我有User
、Article
和Comment
模型。
用户关系:
|_ 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
)
这是正确的方式吗?拉拉维尔的魔法去哪儿了?它看起来很奇怪,景色变得丑陋。
试试这个:
@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;
}));
}