Laravel 4 left join where something equal 或 return zeros

Laravel 4 left join where something is equal Or return zeros

我需要加入两个 table,同时对第二个 table 进行求和和计数。 我已经完成了,但只有当行存在于第二个 table.

如果那里什么都没有,我希望连接到 return 个零,而不是停止显示整行。

我确定我需要在 uid = uid 和 gid = gid 上左连接,但我不确定如何做?

这是我的工作,但过滤了太多代码:

$result = Users_team::where('users_teams.gid', '=', $gid)
                        ->leftjoin('events_users', 'users_teams.uid', '=', 'events_users.uid')
                        ->where('events_users.gid', '=', $gid)
                        ->groupBy('users_teams.uid')
                        ->addSelect( array(
                        '*',
                        DB::raw('count(*) as apps'),
                        DB::raw( 'SUM(goals) AS goals' ),
                        DB::raw( 'SUM(assists) AS assists' ),
                        DB::raw( 'SUM(award) AS awards' ),
                        ));

所以答案是不要在左连接内做一个单独的 'where',这会有效地撤消它的 'left' 部分。

相反,应该在两个条件下进行连接,如下所示。

$result = Users_team::where('users_teams.gid', '=', $gid)
                        ->leftJoin('events_users', function($join)
                            {
                                $join->on('users_teams.uid', '=', 'events_users.uid')
                                ->on('events_users.gid', '=', 'users_teams.gid');
                            })
                        ->groupBy('users_teams.uid')
                        ->addSelect( array(
                        '*',
                        DB::raw('count(*) as apps'),
                        DB::raw( 'SUM(goals) AS goals' ),
                        DB::raw( 'SUM(assists) AS assists' ),
                        DB::raw( 'SUM(award) AS awards' ),
                        ));