使用join和groupBy进行laravel复杂查询构建

时间:2016-07-18 12:59:22

标签: php mysql laravel orm

我是laravel的新手,并且在核心PHP中有以下查询,需要进行laravel查询。

$query="select distinct(c.c_id), 1 'companyToken',c.companyname,u.email,creation_date,CONCAT(eu.firstname,' ',eu.lastname) 'Name' , group_concat(pk.package_name) 'Package Name/Service' ,  c.notes 'Notes' , c.demo_status 'Demo Status'  from ee_company c
                 left join et_company_payment_methods cpm on cpm.c_id=c.c_id
                 left join et_packages pk on cpm.package_id = pk.id
                 inner join (SELECT *
                 FROM `ee_users`
                 WHERE c_id IS NOT NULL
                 GROUP BY c_id) u on u.c_id=c.c_id
                 left join ee_users eu on eu.id=c.referred_by_user_id
                group by c.c_id";

我刚刚开始使用laravel,因此很难转换出如此复杂的查询。

现有系统可以正常使用此查询。

我尝试用laravel建造它。

$company = DB::table('ee_company')
            ->leftJoin('et_company_payment_methods', 'ee_company.c_id' , '=', 'et_company_payment_methods.c_id')
            ->leftJoin('et_packages', 'et_packages.id', '=', 'et_company_payment_methods.package_id')
            ->join('ee_users',function($join){
                                  $join->on('ee_company.c_id', '=', 'ee_users.c_id')
                                     ->whereNotNull('ee_users.c_id')
                                     ->groupBy('ee_users.c_id');
                })
            ->leftJoin('ee_users', 'ee_users.id', '=', 'ee_company.referred_by_user_id')
            ->groupBy('ee_company.c_id');

它给了我以下错误

Call to undefined method Illuminate\Database\Query\JoinClause::groupBy()

1 个答案:

答案 0 :(得分:0)

试试这个

$company = DB::table('ee_company')
        ->leftJoin('et_company_payment_methods', 'ee_company.c_id' , '=', 'et_company_payment_methods.c_id')
        ->leftJoin('et_packages', 'et_packages.id', '=','et_company_payment_methods.package_id')
->join(DB::raw('SELECT *
             FROM `ee_users`
             WHERE c_id IS NOT NULL
             GROUP BY c_id'),function($join){
                              $join->on('u.c_id', '=', 'c.c_id');
            })
->leftJoin('ee_users', 'ee_users.id', '=', 'ee_company.referred_by_user_id')
->groupBy('ee_company.c_id');