php - 使用 GroupBy 计算在 Laravel 中不起作用

标签 php mysql laravel-5

我想要用户之间的聊天计数,并按他们的聊天 ID 分组。但是查询没有给出聊天次数。它的空白。我在 Stack Overflow ( Laravel Eloquent groupBy() AND count , Laravel 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] => 
    )

)

最佳答案

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

这应该可以,我现在无法测试

关于php - 使用 GroupBy 计算在 Laravel 中不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37134923/

相关文章:

mysql - 丢弃字段的最后 3 个字符

php - 可点击获取的数据: Website Redirect

c++ - 消息: [unixODBC][Driver Manager]Can't open lib 'MySQL ODBC 5.1 Driver' : file not foundnSQLSTATE: 01000

node.js - 在 cli 中运行 gulp 时未找到 Laravel Elixir

javascript - 在页面加载时加载函数不会加载 Laravel 5.0

php - 仅显示我和 friend 的迷你博客

php - 根据第一列值合并两个索引数组的索引数组

php - 处理要插入 UTF-8 数据库的 CSV 数据编码

laravel-5 - 在Laravel 5的重置密码中用真实域名替换localhost

php - UnixODBC 多个数据源不起作用