我有一个Posts
和一个Comments
表,其中每个帖子都有多条评论。
我想创建一个获取所有帖子的查询,以及所有已登录用户的评论。
这是我到目前为止所做的:
$posts = Post::select('posts.*')
->with(['comments' => function($query) {
if (Auth::check()) {
$query->where('user_id', Auth::user()->id);
}
}])
->get();
我的Post.php
模型类看起来像这样:
class Post extends Model
{
public function comments()
{
return $this->hasMany('App\Comment');
}
}
当用户登录时,查询会返回正确的结果。
但是当用户不登录时,它会返回所有用户的评论,而不是不返回任何内容(因为用户已登录,因此他们没有评论)。
我该如何解决这个问题?
答案 0 :(得分:1)
我可以通过两种方式来考虑这个问题。
首先,您只能在用户登录时加载评论:
$posts = Post::select('posts.*');
if(Auth::check()) {
$posts->with(['comments' => function($query) {
$query->where('user_id', Auth::user()->id);
}]);
}
$posts = $posts->get();
或者您可以加载所有评论,但如果用户未登录则将user_id
设置为null。由于每条评论都应该有user_id
,因此不会返回任何评论。
$posts = Post::select('posts.*')
->with(['comments' => function($query) {
$query->where('user_id', Auth::check() ? Auth::id() : null);
}])
->get();
第二个中的代码看起来更清晰IMO,但第一个代码将阻止执行不必要的查询。
答案 1 :(得分:0)
你可以将它分开,更清晰,更实用:
$posts = Post::all();
在Post模型中创建一个将返回所有用户评论的函数:
public function userComments()
{
return $this->comments->where('user_id', Auth::user()->id);
}
我想你认为你有一个foreach来迭代所有帖子,在你的foreach里面加载帖子的评论,所以你可以这样做:
@foreach($posts as $post)
$post->userComments()
@endforeach
答案 2 :(得分:0)
您可以在帖子模型中做一些技巧:
class Post extends Model
{
public function comments()
{
if(Auth::check()) {
return $this->hasMany('App\Comment')->where('user_id', Auth::user()->id);
}else{
return $this->hasMany('App\Comment')->where('user_id',-1);
}
}
}
然后简单地:
$posts = Post::select('posts.*')->with('comments')->get()
因此,如果用户未登录,它将返回所有user_id为“ -1”的注释,这将是空