Laravel-汇总结果未给出正确的结果

时间:2019-06-15 17:19:33

标签: laravel eloquent

我希望结果显示在图中:

incorrect result

但是我得到以下结果:

wrong result

该:

  1. 每行总活动用户为0,这是不正确的

  2. 每行总无效用户为0,这是不正确的

  3. 每行的总用户数为44,并且全部相同,这是不正确的

请参见下面的代码:

        $subscribers= Cloudsubscriptions::join("services","cloudsubscriptions.service_name","=","services.name")
        ->join("service_type","services.service_type","=","service_type.id")
        ->select("cloudsubscriptions.service_name"
                ,"service_type.name as service_type"
                ,DB::raw("(SELECT count(cloudsubscriptions.id) FROM cloudsubscriptions WHERE('cloudsubscriptions.is_subscribe' = 1)) as total_active_users")
                ,DB::raw("(SELECT count(cloudsubscriptions.id) FROM cloudsubscriptions WHERE('cloudsubscriptions.is_subscribe' = 0)) as total_inactive_users")
                ,DB::raw("(SELECT count(cloudsubscriptions.id) FROM cloudsubscriptions) as total_users"))
        ->groupBy("cloudsubscriptions.service_name")
    ->get();

我在哪里弄错了?

1 个答案:

答案 0 :(得分:0)

使用此查询。

$subscribers= DB::table('cloudsubscriptions')
    ->join("services","cloudsubscriptions.service_name","=","services.name")
    ->join("service_type","services.service_type","=","service_type.id")
    ->select("cloudsubscriptions.service_name"
            ,"service_type.name as service_type"
            ,DB::raw("(SELECT count(*) FROM cloudsubscriptions WHERE is_subscribe = 1 AND services.name = cloudsubscriptions.service_name) as total_active_users")
            ,DB::raw("(SELECT count(*) FROM cloudsubscriptions WHERE is_subscribe = 0 AND services.name = cloudsubscriptions.service_name) as total_inactive_users")
            ,DB::raw("(SELECT count(*) FROM cloudsubscriptions WHERE services.name = cloudsubscriptions.service_name) as total_users"))
    ->groupBy("cloudsubscriptions.service_name")
->get();

从我的角度来看,这是非常糟糕的做法。您与laravel有雄辩的关系。雄辩的关系将使您的工作更加轻松。