我有3个名为user,group和user_has_group的表。我正在使用雄辩的方式加入这些表格。一切都很好,但我还需要更多东西。我需要弄清楚哪个组有多少用户。这里是我使用的I代码:
$result = UserHasGroup
::join('group', 'user_has_group.group_id', '=', 'group.id')
->join('user', 'group.created_by', '=', 'user.id')
->where('user_has_group.user_id', '=', $user -> id)
->select("user.name as created_by",
'group.created_at',
'user_has_group.user_id',
'group.name as group_name')
->getQuery()
->get();
这是响应:
{
"successful": [
{
"created_by": "TUSHAR13",
"created_at": "2018-05-11 18:04:38",
"user_id": "5",
"group_name": "DSGJA"
},
{
"created_by": "TUSHAR13",
"created_at": "2018-05-11 18:10:17",
"user_id": "5",
"group_name": "V76OL"
},
{
"created_by": "TUSHAR13",
"created_at": "2018-05-10 00:00:00",
"user_id": "5",
"group_name": "qwerr"
}
]
}
现在我无法理解在哪里添加groupby和count查询。我需要帮助。
答案 0 :(得分:1)
$result = UserHasGroup
::join('group', 'user_has_group.group_id', '=', 'group.id')
->join('user', 'group.created_by', '=', 'user.id')
->select("user.name as created_by",
'group.created_at',
'user_has_group.user_id',
'group.name as group_name', DB::raw('count(*) as total'))
->groupBy('user_id')
->getQuery()
->get();
您必须在DB::raw('Count(*)')
中使用select()
,然后按user_id使用群组。
希望这会有所帮助。