laravel - 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();
解决方案
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
,可以让您计算我假设的未读消息。
推荐阅读
- axios - 阻止 axios 发送选项请求
- material-ui - 什么用纸或卡片?
- google-data-studio - DataStudio SUM 文本字段(如果包含“utm_source = 'google'”)[关闭]
- java - 这个 DateTime 的 JSON 格式模式是什么?
- python - 将 Python Tkinter IntVar() 列表转换为常规 int 列表?
- azure - Azure B2C 与 Azure 应用程序网关和基于路径的后端池
- python - Pandas:从数据框中删除大量重复数字的重复项
- ssl - 通过 SSL 使用 JDBC 和 PySpark
- python - 标准化或标准化分类值
- c++ - 对浮点值数组求和的最快方法