DB :: raw转换为查询生成器

时间:2019-08-16 14:07:17

标签: laravel laravel-5 eloquent laravel-query-builder

您能帮我将查询的Raw部分转换为使用查询生成器吗?
我一直坚持将所有内容结合在一起:

$profile = UserProfiles::select('id')->where('alias', $profileAlias)->first();

$dbRawMessagesCount = '
  (SELECT COUNT(pm.id) 
  FROM profile_messages pm 
  WHERE pm.to_profile_id='.$profile->id.' 
     AND pm.from_profile_id=profile_friend.id 
     AND pm.is_read=0) AS messages_count
';

$friends = ProfileFriend::select('profile_friend.*', DB::raw($dbRawMessagesCount))
    ->with('friendProfile')
    ->whereHas('ownerProfile', function ($query) use ($profile) {
        return $query->where('id', $profile->id);
    })
    ->orderBy('messages_count')
    ->paginate();

1 个答案:

答案 0 :(得分:1)

如果在查询中使用ProfileFriendProfileMessages已将关系设置为withCount(),则可以将其重写为一个查询。

$friends = ProfileFriend::with('friendProfile')
    ->withCount(['profileMessages' => function($q) use($profile){
        $q->where('to_profile_id', $profile->id)->where('is_read', 0); 
        // No longer need 'from_profile_id' as it is already querying the relationship
    }])
    ->whereHas('ownerProfile', function ($query) use ($profile) {
        return $query->where('id', $profile->id);
    })
    ->paginate();

现在,如果您dd($friends->first()),您会注意到它有一个名为profileMessages_count的字段,该字段为您提供了我认为未读邮件的数量。

相关问题