Eloquent - 获取关系为布尔值的模型

Eloquent - Get Model with relationship as boolean

我的模型具有以下 one-to-many 关系

class Comment extends Model
{
    public function likes(): HasMany
    {
        return $this->hasMany(CommentLike::class);
    }
}

在我的 Controller 中,我想获取所有 Comments 以及一个布尔值,该值指示当前用户是否存在于 likes table

$result = Comment::with(['user', 'likes' => function($q) use($user){
  $q->where('user_id', $user->id);
}])
  ->withCount('likes')
  ->where('post_id', $postId)
  ->get();

目前,如果找到用户,上面的查询将 return 正确的结果以及喜欢的一行 table。

我正在寻找一种正确的方法来 return 一个布尔值来指示用户是否喜欢该评论。

首先,您可以通过这种方式了解用户对评论的点赞数。

$likes = Comment::whereHas(['likes' => function($q) use ($user){
          $q->where('user_id', $user->id);
         })->where('post_id', $postId)->count();

然后使用 $likes 变量值,您可以有条件地创建一个布尔值并分配给新变量或相同的 $likes 变量。

$hasLike = $likes ? true : false;

您可以使用withExists()方法。它不是最好的记录之一,但我认为它很简单。

在你的例子中:

$result = Comment::with(['user', 'likes' => function($q) use($user){
        $q->where('user_id', $user->id);
    }])
    ->withCount('likes')
    ->where('post_id', $postId)
    ->get();

考虑将其更改为:

$result = Comment::with(['user', 'likes'])
    ->withCount('likes')
    ->withExists(['likes' => function ($query) use ($user) {
        $query->where('user_id', $user->id);
    }])
    ->where('post_id', $postId)
    ->get();

结果模型将包含额外的布尔值 属性 likes_exists 其中 true 表示 $user 喜欢该评论,而 false 表示他们不喜欢它。