doujia9204 2019-03-07 00: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 00: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条)
编辑
预览

报告相同问题?

手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部