首页 > 解决方案 > DB::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();

标签: laravellaravel-5eloquentlaravel-query-builder

解决方案


ProfileFriend如果已经设置了在查询中ProfileMessages使用的关系,您可以将其重写为一个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,可以让您计算我假设的未读消息。


推荐阅读