結論
laravel 5.6.3から
joinSub、leftJoinSubが使える.
$subQuery = ProfileUserView::select(['user_id', 'company_id'])
->whereBetween('created_at', [$from, $to])
->distinct();
$mostViewQuery = \DB::query()
->selectRaw('company_id, COUNT(user_id) AS pv')
->fromSub($subQuery, 'sub')
->groupBy('company_id');
ver 5.6.3以前
それより以前は mergeBindings使う.
$count = DB::table( DB::raw("({$sub->toSql()}) as sub") )
->mergeBindings($sub->getQuery()) // you need to get underlying Query Builder
->count();
こんな感じ
$subQuery = ProfileUserView::select(['user_id', 'company_id'])
->whereBetween('created_at', [$from, $to])
->distinct();
$mostViewQuery = \DB::table(\DB::raw("({$subQuery->toSql()}) as sub") )
->mergeBindings($subQuery->getQuery())
->selectRaw('company_id, COUNT(user_id) AS pv')
->groupBy('company_id');
ただしmergeBindingsは、bindするパラメーターの順序を気をつけないといけないので注意する