简体   繁体   English

Laravel在一个查询中进行不同选择

[英]Laravel different selects in one query

I will try to describe my situation; 我将尝试描述我的处境; I have two separate queries below: 我在下面有两个单独的查询:

   public function getDriversCount($request) {
      return Driver::count();
   }

and the second one: 第二个:

public function getDriversCountWithStatus($request) {
    return Driver::select('status', DB::raw('count(*) as total'))
                        ->groupBy('status')
                        ->get();
}

now we can see that these two are two separate functions and to separate queries. 现在我们可以看到这两个是两个独立的函数和独立的查询。 In the first one I am counting the whole drivers table records, but in the second one I am counting according to status groups. 在第一个中,我在统计整个drivers表记录,但是在第二个中,我根据status组进行计数。 So how can I achieve the same result by one function and one query? 那么,如何通过一个函数和一个查询来达到相同的结果呢? something like that: 像这样的东西:

{
    "absolute_total": 21,
    "with_status": [
        {
            "status": 0,
            "total": 11
        },
        {
            "status": 1,
            "total": 10
        }
    ]
}

this one I received manually by calling these two functions separately. 我是通过分别调用这两个函数手动收到的。

You can do the below, we set an empty array at the start, so if the function returns an empty array you can do further checking on that: 您可以执行以下操作,我们在开始处设置了一个空数组,因此,如果函数返回一个空数组,您可以对此进行进一步检查:

public function getDriversCountAndStatus($request)
{
    // Set the array that will be returned
    $driversCountWithStatus = [];

    // Get the driver count
    $driverCount = Driver::count();

    // Get the driver status
    $driverStatus = Driver::select('status', DB::raw('count(*) as total'))
                    ->groupBy('status')
                    ->get();

    // Combine the driver count and status into one array
    $driversCountWithStatus = [
        "absolute_total" => $driverCount,
        "with_status" => $driverStatus;
    ];

    return $driversCountWithStatus;
}

I can't comment yet because I don't have enough rep. 我没有评论,因为我没有足够的代表。

I think I understand what you mean. 我想我明白你的意思。 The easiest way to do this would be chaining a couple of selects together. 最简单的方法是将几个选择链接在一起。

Something like 就像是

public function getDriversCountWithStatus($request) {
    return Driver::select('total', DB::raw('count(*) as total'))
        ->addSelect('status', DB::raw('count(*) as total group by status'))
        ->get();
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM