Laravel查询-从3个不同的表进行计数和分组

时间:2019-07-29 10:54:09

标签: sql laravel

我正在使用LARAVEL和SQL迈出第一步,我正在尝试构建一个查询,该查询返回我拥有的部门列表,同时计算每个部门中的位置总数以及设备的总数。每个位置。

所以我尝试了以下操作:

$dep = DB::table('departments')
       ->leftjoin('locations','departments.dep_id','=','locations.department')
       ->leftjoin('devices','locations.id','=','devices.location')
       ->select('departments.name',DB::raw('count(locations.id) as locationcount'))
       ->groupby('departments.name')
       ->get();

这会给我以下信息:

Illuminate\Support\Collection Object
(
    [items:protected] => Array
        (
            [0] => stdClass Object
                (
                    [name] => Interior Design
                    [locationcount] => 3
                )

            [1] => stdClass Object
                (
                    [name] => IT
                    [locationcount] => 29
                )

            [2] => stdClass Object
                (
                    [name] => Marketing
                    [locationcount] => 0
                )

            [3] => stdClass Object
                (
                    [name] => Operations
                    [locationcount] => 13
                )

        )

但是在这里,我们看到的数量是针对设备而不是位置的。有什么办法可以实现这个查询?还是我需要做一个循环?我正在寻找这样的结果:

Illuminate\Support\Collection Object
    (
        [items:protected] => Array
            (
                [0] => stdClass Object
                    (
                        [name] => Interior Design
                        [locationcount] => 2
                        [devicecount] => 10
                    )

....

1 个答案:

答案 0 :(得分:1)

包括设备的数量,然后修改您当前的逻辑以获取不同的位置数量:

$dep = DB::table('departments')
    ->leftjoin('locations', 'departments.dep_id', '=', 'locations.department')
    ->leftjoin('devices', 'locations.id', '=', 'devices.location')
    ->select('departments.name',
             DB::raw('COUNT(DISTINCT locations.id) AS locationcount'),
             DB::raw('COUNT(devices.id) AS devicecount'))
    ->groupby('departments.name')
    ->get();

之所以可行,是因为纯设备计数已经使用了联接中的最后一个表,因此它应该已经反映了真实计数。对于这些位置,我们采用不重复计数来消除由于加入设备表而可能发生的重复计数。