使用JOIN / SUB查询将SQL转换为Laravel查询生成器

时间:2019-01-14 07:22:59

标签: laravel eloquent laravel-query-builder

SELECT user_sessions.os, COUNT(*) FROM user_sessions
    JOIN (SELECT MIN(created_at) AS MinCreatedAt, user_id FROM user_sessions 
    GROUP BY user_id) AS us2
    ON (user_sessions.created_at = us2.MinCreatedAt 
        AND user_sessions.user_id = us2.user_id 
    GROUP BY user_sessions.os

这是原始SQL查询,我尝试在Eloquent中进行转换,但失败了。我的试用代码是...

$q1 = self::select(DB::raw('MIN(created_at) as MinCreatedAt, user_id'))->groupBy('user_id');
$q2 = self::select(DB::raw('user_sessions.os, count(*)'));

$users = self::
select($q2)->joinSub($q1, 'us2', function ($join) {
$join->on('user_sessions.created_at = us2.MinCreatedAt AND user_sessions.user_id = us2.user_id ');
})->get();

错误

  

stripos()希望参数1是给定的字符串对象

1 个答案:

答案 0 :(得分:0)

尝试这个。

$joinQuery = "(".DB::table('user_sessions')
    ->selectRaw('MIN(created_at) AS MinCreatedAt, user_id')
    ->groupBy('user_id')->toSql().") as us2" ;


$users = DB::table('user_sessions')
        ->selectRaw("user_sessions.os, COUNT(*)")
        ->join(DB::raw($joinQuery), function ($join) {
            $join->on('user_sessions.created_at', '=', 'us2.MinCreatedAt')->on('user_sessions.user_id', '=', 'us2.user_id');
        })
        ->groupBy('user_sessions.os');

更新

$q1 = self::select(DB::raw('MIN(created_at) as MinCreatedAt, user_id'))->groupBy('user_id');
$q2 = self::select(DB::raw('user_sessions.os, count(*)'));

$users = $q2->joinSub($q1, 'us2', function ($join) {
$join->on('user_sessions.created_at = us2.MinCreatedAt AND user_sessions.user_id = us2.user_id ');
})->groupBy('user_sessions.os')->get();