sql查询构建器laravel 4有多个表选择

时间:2016-05-19 14:56:17

标签: laravel-4 query-builder

我想在laravel 4.2的查询构建器中翻译这个sql请求,你能帮帮我吗?

提前致谢!

表api_calls => id | key_id |服务器| created_at

表api_key => id |关键| created_at

SQL:

SELECT K.key FROM api_key as K

WHERE
(SELECT count(id) FROM api_calls WHERE server = $server AND key_id = K.id AND created_at >= $DateSeconds) < 10

AND 
(SELECT count(id) FROM api_calls WHERE server = $server AND key_id = K.id AND created_at >= $DateMinutes) < 500

GROUP BY K.key

1 个答案:

答案 0 :(得分:0)

使用连接ang聚合:

DB::table('api_key as K')
    ->select('K.*')
    ->join('api_calls as ac1', function ($join) use ($server, $DateSeconds) {
        $join->on('ac1.server', '=', DB::raw($server));
        $join->on('ac1.key_id', '=', 'K.id');
        $join->on('ac1.created_at', '>=', DB::raw($DateSeconds));
     })
     ->join('api_calls as ac2', function ($join) use ($server, $DateMinutes) {
        $join->on('ac2.server', '=', DB::raw($server));
        $join->on('ac2.key_id', '=', 'K.id');
        $join->on('ac2.created_at', '>=', DB::raw($DateMinutes));
     })
     ->having(DB::raw('COUNT(ac1.id)'), '<', 10)
     ->having(DB::raw('COUNT(ac2.id)'), '<', 500)
     ->groupBy('K.id')
     ->get();