使用聚合方法将SQL转换为Eloquent

时间:2015-04-21 08:28:57

标签: mysql laravel eloquent

如何将该SQL查询转换为Eloquent模式在Laravel 4中:

SELECT count(distinct(worker_id)) FROM formation_worker WHERE formation_id in(SELECT id FROM formations WHERE YEAR(start_date)=YEAR(now()))

此致

2 个答案:

答案 0 :(得分:1)

FormationWorker::select(DB::raw('count(distinct(worker_id))'))
    ->whereIn('formation', function($sq) {
        $sq->select('id')
           ->from('formations')
           ->whereRaw('YEAR(start_date)=YEAR(now())');
    });

答案 1 :(得分:0)

这是我在@limonte回复中的解决方案:

DB::table('formation_worker')
                            ->select(DB::raw('count(distinct(worker_id))'))
                                ->whereIn('formation_id', function($sq) {
                                    $sq->select('id')
                                       ->from('formations')
                                       ->whereRaw('YEAR(start_date)=YEAR(now())');
                                })->first()