7
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

【Laravel】 From句にサブクエリを使用する

Last updated at Posted at 2020-03-25

結論

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するパラメーターの順序を気をつけないといけないので注意する

7
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
7
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?