LoginSignup
5
3

More than 5 years have passed since last update.

[Eloquent]Union()で重複行があるのでdistinctしたい

Last updated at Posted at 2018-01-17

処理の順番がおかしい可能性がある

現状

UNION_ALLと同じ

$first = DB::table('users')
    ->whereNull('first_name')
    ->get();

$users = DB::table('users')
    ->whereNull('last_name')
    ->get()
    ->union($first);

これだと、$firstと$userがそれぞれget()した形がunion()されるのでUNION ALLと同等になる。

改善

UNIONになる
$first = DB::table('users')
    ->whereNull('first_name');

$users = DB::table('users')
    ->whereNull('last_name')
    ->union($first)
    ->get();

クエリを持った状態でget()前にunionするため、UNION ALLとならない

thanks

UNION DISTINCT in laravel query builder - Stack Overflow

5
3
1

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
5
3