Return 仅当用户登录时才有关系?

Return relationship only if user is logged in?

我有一个 Posts 和一个 Comments table,其中每个 post 可以有多个评论。

我想进行查询以获取所有 post 以及所有已登录用户的评论。

这是我目前的情况:

$posts = Post::select('posts.*')
    ->with(['comments' => function($query) {
        if (Auth::check()) {
            $query->where('user_id', Auth::user()->id);
        }
    }])
    ->get();

我的 Post.php 模型 class 看起来像这样:

class Post extends Model
{
    public function comments()
    {
        return $this->hasMany('App\Comment');
    }
}

用户登录时查询returns正确结果

但是当用户登录时,它returns所有用户的评论,而不是什么都不返回(因为用户已登录,因此他们没有意见)。

我该如何解决这个问题?

可以分开,更清晰实用:

$posts = Post::all();

在您的 Post 模型中创建一个函数,该函数将 return 所有用户的评论:

public function userComments()
{
    return $this->comments->where('user_id', Auth::user()->id);
}

而且我猜你认为你有一个 foreach 来迭代所有 posts,在你的 foreach 中你加载 post 的评论,所以你可以这样做:

@foreach($posts as $post)
    $post->userComments()
@endforeach

我可以想到两种方法。

首先,如果用户已登录,您只能加载评论:

$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();

第二个中的代码在我看来更清晰,但第一个会阻止执行不必要的查询。

你可以在你的 post 模型中做一些小技巧:

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()

因此,如果用户未登录,它将 return 所有带有 user_id 的“-1”的评论,这将是空的