Laravel-汇总函数中的语法错误或访问冲突

时间:2019-06-15 14:02:26

标签: laravel eloquent

我想执行聚合功能并实现下图中所示的结果:

summary

新结果:

incorrect result

我有这个查询:

        $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 'is_subscribe' = 1) as total_active_users")
                    ,DB::raw("(SELECT count(cloudsubscriptions.id) FROM 'cloudsubscriptions' WHERE 'is_subscribe' = 0) as total_inactive_users")
                    ,DB::raw("(SELECT count(cloudsubscriptions.id) FROM 'cloudsubscriptions') as total_users"))
            ->groupBy("cloudsubscriptions.service_name")
        ->get();

我希望在图中显示结果,但出现此错误

  

“ SQLSTATE [42000]:语法错误或访问冲突:1064您的SQL语法有错误;请查看与您的MariaDB服务器版本相对应的手册,以获取在'cloudsubscriptions'中使用的正确语法,其中'is_subscribe' = 1)作为total_active_users,(第1行的SELECT co'(SQL:选择cloudsubscriptionsservice_nameservice_typenameservice_type,(SELECT计数(cloudsubscriptions.id)来自'cloudsubscriptions'其中'is_subscribe'= 1)作为total_active_users,(SELECT count(cloudsubscriptions.id)来自'cloudsubscriptions'WHERE'is_subscribe'= 0)作为total_inactive_users,(SELECT count(cloudsubscriptions.id)FROM “ cloudsubscriptions”)来自cloudsubscriptionsservices个内部联接cloudsubscriptions的total_users。service_name = servicesname内部联接service_typeservices上。service_type = service_typeidcloudsubscriptions分组。service_nameservice_name排序,升序限制15偏移量0) ◀”

我该如何解决?

1 个答案:

答案 0 :(得分:1)

该错误是由原始表达式中的表名和列名引起的单引号引起的。

删除它们或使用反引号:

$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 `is_subscribe` = 1) as total_active_users")
            ,DB::raw("(SELECT count(cloudsubscriptions.id) FROM `cloudsubscriptions` WHERE `is_subscribe` = 0) as total_inactive_users")
            ,DB::raw("(SELECT count(cloudsubscriptions.id) FROM `cloudsubscriptions`) as total_users"))
    ->groupBy("cloudsubscriptions.service_name")                ^                  ^
->get();