算得上GroupBy不在Laravel工作

时间:2016-05-10 09:50:26

标签: php mysql laravel-5

我想要用户之间的聊天计数和按聊天ID分组。但查询没有给出聊天计数。它的空白。我已经在Stack Overflow(Laravel Eloquent groupBy() AND countLaravel get count of results based on groupBy)中看到了类似的问题,并使用那些标记为正确但仍未获得所需结果的查询。

我使用以下查询:

$user_info = DB::table('chat_messages')
                ->select(DB::raw('count(*) as total'))
                ->where('viewed','=', '0')
                ->groupBy('chat_id','type')
                ->get();

我的表结构如下:

{
"_id": ObjectId("571f549b1c8cb6972c8b4567"),
"message": "Testing Chat Functionality",
"type": "singlechat",
"date": "2016-04-26 11:44:27",
"from": "56b07a5a083f119a0b8b4569",
"to": "56b07a5a083f119a0b8b4569",
"chat_id": "56f65fc51c8cb6ca1a8b4567",
"status": "1",
"updated_at": ISODate("2016-04-26T11:44:27.624Z"),
"created_at": ISODate("2016-04-26T11:44:27.624Z"),
"viewed": "0"
}

结果是这样的:

Array
(
[0] => Array
    (
        [_id] => Array
            (
                [chat_id] => 56f65fc51c8cb6ca1a8b4567
                [type] => singlechat
            )

        [chat_id] => 56f65fc51c8cb6ca1a8b4567
        [type] => singlechat
        [count(*) as total] => 
    )

[1] => Array
    (
        [_id] => Array
            (
                [chat_id] => 56fa3f5f1c8cb667138b4567
                [type] => groupchat
            )

        [chat_id] => 56fa3f5f1c8cb667138b4567
        [type] => groupchat
        [count(*) as total] => 
    )

2 个答案:

答案 0 :(得分:0)

$user_info = DB::table('chat_messages')
                ->where('viewed','=', '0')
                ->select(DB::raw('count(chat_messages.*) as total'))
                ->groupBy('chat_id','type')
                ->get();

这应该有用,我现在无法测试

答案 1 :(得分:0)

试试这段代码。

 $this->select(\DB::raw("*, count(*) as total"))
->where('viewed', "0")
->groupBy(["chat_id", "type"]);