Laravel每个用户的计数如何

时间:2016-12-05 08:17:48

标签: php mysql sql laravel query-builder

我想在结果3字段中检索每个用户的wallsfollowexos计数。

以下代码为每个字段提供相同的计数:

$profils = \DB::table('users')
->select(['users.*',\DB::raw('count(follow.user_id) as likeme'), \DB::raw('count(murs.user_id) as murme'), \DB::raw('count(exos.user_id) as exome')])
        ->leftjoin('murs', 'users.id', '=', 'murs.user_id')
        ->leftjoin('exos', 'users.id', '=', 'exos.user_id')             
        ->leftjoin('follow', 'users.id', '=', 'follow.user_id')
        ->groupby('users.id')
        ->paginate(15);

1 个答案:

答案 0 :(得分:0)

尝试以下代码:

$profils = \DB::table('users')
->select(['users.*',\DB::raw('count(DISTINCT(follow.user_id)) as likeme'), \DB::raw('count(DISTINCT(murs.user_id)) as murme'), \DB::raw('count(DISTINCT(exos.user_id)) as exome')])
        ->leftjoin('murs', 'users.id', '=', 'murs.user_id')
        ->leftjoin('exos', 'users.id', '=', 'exos.user_id')             
        ->leftjoin('follow', 'users.id', '=', 'follow.user_id')
        ->groupby('users.id')
        ->paginate(15);

如果这不适合你,请告诉我。