doujia9204 2019-03-07 08:48
浏览 165
已采纳

Laravel将数据计数附加到数据库对象

Hello i have this function

public function readData(){
$TableB1 = \DB::table('users')
->join('group_user', 'users.id', '=', 'group_user.user_id')
->join('groups', 'groups.id', '=', 'group_user.group_id')
->join('meetings', 'users.id', '=', 'meetings.owned_by_id')
->select(
   'users.name as name',
   'group_user.user_id as id',
   'groups.name as groupname',
    )
->get();
foreach ($TableB1 as &$data){
    $meetings = \DB::table('meetings')
                ->where('company_id', 1)->where('owned_by_id', $data->id)
                ->where(\DB::raw('MONTH(created_at)'), Carbon::today()->month);
    echo $meetings->count();
}

return $TableB1;

}

i retrieve some data from database and return them and use AJAX Call to use them later

The problem is i have a table called users and table called meetings

i want to know how many meetings every user done everyday

so to do this i made a for each to take the user_id and use it to get the count of meetings done by each user

for example in meetings table i have a owned_by_id field which have the user_id

so what the code does if it found for example if owned_by_id(6) repeated in

meetings table 4 times it will return 4

but this is what i get in the browser

instead what i want to get is something like this

im using Laravel 5.7 and sorry i know my question is unclear this is the 1st time i have ever asked question on stackoverflow Image

  • 写回答

2条回答 默认 最新

  • duanlan3598 2019-03-07 08:54
    关注

    You could add a new column in the select() using the COUNT SQL statement:

    ->select(
        'users.name as name',
        'group_user.user_id as id',
        'groups.name as groupname',
        \DB::raw('(
            SELECT COUNT(meetings.id) FROM meetings GROUP BY meetings.owned_by_id
        ) as meetings')
    )
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 mmocr的训练错误,结果全为0
  • ¥15 python的qt5界面
  • ¥15 无线电能传输系统MATLAB仿真问题
  • ¥50 如何用脚本实现输入法的热键设置
  • ¥20 我想使用一些网络协议或者部分协议也行,主要想实现类似于traceroute的一定步长内的路由拓扑功能
  • ¥30 深度学习,前后端连接
  • ¥15 孟德尔随机化结果不一致
  • ¥15 apm2.8飞控罗盘bad health,加速度计校准失败
  • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线
  • ¥15 谁有desed数据集呀