ホーム>Laravel>【Laravel】unionで違うテーブル同士を一緒に取得する方法(Eloquent・unionAll・orderBy)
Laravel

【Laravel】unionで違うテーブル同士を一緒に取得する方法(Eloquent・unionAll・orderBy)

いつもご利用ありがとうございます。
この記事にはアフィリエイト広告を含む広告が掲載されており、その広告費によって運営しています。
Amazonのアソシエイトとして、ララテックは適格販売により収入を得ています。

Laravelのunionで、postsとitemsのような違うテーブルを1つの一覧として取得する方法です。Eloquentでの書き方、whereをかける場所、unionAllとの違い、orderByとpaginate、カラム数が違うときのエラーを、Laravel 13とMySQL 8.4で確かめた結果つきでまとめました。

Union を使うケースを考える

例えば、ユーザーが記事と商品を投稿できるサービスがあるとして、それぞれ詳細ページがあるとします。

そこで、これら3つのテーブルをガッチャンコした上で

ユーザー
記事
商品

一覧化したいときに使えます。

他にも使う用途はおそらくあると思うので、もしあったらぜひ教えてください!

Union を使う方法

Union()を使う方法は至って簡単です。

コントーラーなどで、

  use App\Models\Item;
  use App\Models\Post;

~~~
public function index()
{
  $items = Item::select('title','created_at');
  $results = Post::select('title','created_at')
      ->union($items)
      ->get();
  dd($results);
}

こんな感じで書けば OK です。

union の()の中に、取得したい Eloquent を書いてあげるだけです。

Laravel 13 で実行した SQL と結果

2026年11月に、Docker の php:8.4-cli(PHP 8.4.27)・Laravel 13.42.0・MySQL 8.4.13 で、上のコードを動かして確かめました。

posts と items に、次のデータを3件ずつ入れています。

テーブルtitlecreated_at
posts記事A2026-11-01 10:00:00
posts(null)2026-11-03 10:00:00
postsお知らせ2026-11-05 10:00:00
items商品A2026-11-02 10:00:00
items(null)2026-11-04 10:00:00
itemsお知らせ2026-11-05 10:00:00

toRawSql() で見た SQL と、get() の結果はこうでした。

(select `title`, `created_at` from `posts`) union (select `title`, `created_at` from `items`)

App\Models\Post {"title":"記事A","created_at":"2026-11-01 10:00:00"}
App\Models\Post {"title":null,"created_at":"2026-11-03 10:00:00"}
App\Models\Post {"title":"お知らせ","created_at":"2026-11-05 10:00:00"}
App\Models\Post {"title":"商品A","created_at":"2026-11-02 10:00:00"}
App\Models\Post {"title":null,"created_at":"2026-11-04 10:00:00"}

6件入れたのに、結果は5件です。

posts と items の「お知らせ」は title と created_at がまったく同じなので、union が重複として1件にまとめました。

また、items から来た「商品A」の行も、App\Models\Item ではなく App\Models\Post のモデルになっていました。

Eloquent の union は、元になった側(ここでは Post)のモデルで結果を作るので、items の行で Item のリレーションやアクセサは使えません。

items の行かどうかを見分けたいときは、下の「どちらのテーブルの行かを見分ける」のようにカラムを足します。

where を使って検索する

タイトルのある item と post を取得する

例えばこうなります

$results = Post::select('title','created_at')
    ->union($items)
    ->whereNotNull('title')
    ->get();

(2026-11-12 訂正)この書き方では、whereNotNull は posts の側にしかかかりません。

Laravel 13 で確かめたところ、SQL は次のようになり、タイトルが null の item が残りました。

(select `title`, `created_at` from `posts` where `title` is not null) union (select `title`, `created_at` from `items`)

App\Models\Post {"title":"記事A","created_at":"2026-11-01 10:00:00"}
App\Models\Post {"title":"お知らせ","created_at":"2026-11-05 10:00:00"}
App\Models\Post {"title":"商品A","created_at":"2026-11-02 10:00:00"}
App\Models\Post {"title":null,"created_at":"2026-11-04 10:00:00"}

->union() の後ろに書いた where も、1つ目の select の中に入ります。

タイトルのある item と post の両方を取りたいときは、それぞれのクエリに where を書きます。

$items = Item::select('title','created_at')
    ->whereNotNull('title');
$results = Post::select('title','created_at')
    ->whereNotNull('title')
    ->union($items)
    ->get();
(select `title`, `created_at` from `posts` where `title` is not null) union (select `title`, `created_at` from `items` where `title` is not null)

App\Models\Post {"title":"記事A","created_at":"2026-11-01 10:00:00"}
App\Models\Post {"title":"お知らせ","created_at":"2026-11-05 10:00:00"}
App\Models\Post {"title":"商品A","created_at":"2026-11-02 10:00:00"}

null の行が両方から消えました。

全ての post とタイトルのある item を取得する

$items = Item::select('title','created_at')
  ->whereNotNull('title');
$results = Post::select('title','created_at')
    ->union($items)
    ->get();
dd($results);

このように、union の()の中で where してしまえば良いです。

Laravel 13 でも、items の側だけに where が入りました。

(select `title`, `created_at` from `posts`) union (select `title`, `created_at` from `items` where `title` is not null)

App\Models\Post {"title":"記事A","created_at":"2026-11-01 10:00:00"}
App\Models\Post {"title":null,"created_at":"2026-11-03 10:00:00"}
App\Models\Post {"title":"お知らせ","created_at":"2026-11-05 10:00:00"}
App\Models\Post {"title":"商品A","created_at":"2026-11-02 10:00:00"}

重複を消さない unionAll

同じ行を1件にまとめたくないときは、unionAll() を使います。

$items = Item::select('title','created_at');
$results = Post::select('title','created_at')
    ->unionAll($items)
    ->get();

Laravel 13 で確かめると、SQL が union all になり、「お知らせ」が2件とも残って6件になりました。

(select `title`, `created_at` from `posts`) union all (select `title`, `created_at` from `items`)

App\Models\Post {"title":"記事A","created_at":"2026-11-01 10:00:00"}
App\Models\Post {"title":null,"created_at":"2026-11-03 10:00:00"}
App\Models\Post {"title":"お知らせ","created_at":"2026-11-05 10:00:00"}
App\Models\Post {"title":"商品A","created_at":"2026-11-02 10:00:00"}
App\Models\Post {"title":null,"created_at":"2026-11-04 10:00:00"}
App\Models\Post {"title":"お知らせ","created_at":"2026-11-05 10:00:00"}

記事と商品のように別々のものを並べるときは、たまたま同じ値の行が消えてしまわないよう、unionAll か、下の「種類」のカラムを足すほうが安心です。

新しい順に並べる(orderBy)

タイムラインのように新しい順で並べたいときは、union() の後ろに orderBy() を書きます。

$items = Item::select('title','created_at');
$results = Post::select('title','created_at')
    ->union($items)
    ->orderBy('created_at', 'desc')
    ->get();

where と違い、orderBy は union 全体の外側に付きました。

(select `title`, `created_at` from `posts`) union (select `title`, `created_at` from `items`) order by `created_at` desc

App\Models\Post {"title":"お知らせ","created_at":"2026-11-05 10:00:00"}
App\Models\Post {"title":null,"created_at":"2026-11-04 10:00:00"}
App\Models\Post {"title":null,"created_at":"2026-11-03 10:00:00"}
App\Models\Post {"title":"商品A","created_at":"2026-11-02 10:00:00"}
App\Models\Post {"title":"記事A","created_at":"2026-11-01 10:00:00"}

posts と items が混ざって、日付の新しい順になっています。

paginate も使える

一覧ページにするなら paginate() もそのまま付けられました。

$results = Post::select('title','created_at')
    ->union($items)
    ->orderBy('created_at', 'desc')
    ->paginate(2);

実行された SQL を DB::getQueryLog() で見ると、件数は union 全体をサブクエリにして数えていました。

total=5 lastPage=3
select count(*) as `aggregate` from ((select `title`, `created_at` from `posts`) union (select `title`, `created_at` from `items`)) as `temp_table`
(select `title`, `created_at` from `posts`) union (select `title`, `created_at` from `items`) order by `created_at` desc limit 2 offset 0

どちらのテーブルの行かを見分ける

結果はすべて Post のモデルになるので、詳細ページへのリンクを作るときなどに、記事か商品かが分かりません。

そこで、DB::raw() で固定の文字を返すカラムを足しておきます。

use Illuminate\Support\Facades\DB;

$items = Item::select('id', 'title', 'created_at', DB::raw("'item' as type"));
$results = Post::select('id', 'title', 'created_at', DB::raw("'post' as type"))
    ->union($items)
    ->orderBy('created_at', 'desc')
    ->get();
(select `id`, `title`, `created_at`, 'post' as type from `posts`) union (select `id`, `title`, `created_at`, 'item' as type from `items`) order by `created_at` desc

App\Models\Post {"id":3,"title":"お知らせ","created_at":"2026-11-05 10:00:00","type":"post"}
App\Models\Post {"id":3,"title":"お知らせ","created_at":"2026-11-05 10:00:00","type":"item"}
App\Models\Post {"id":2,"title":null,"created_at":"2026-11-04 10:00:00","type":"item"}
App\Models\Post {"id":2,"title":null,"created_at":"2026-11-03 10:00:00","type":"post"}
App\Models\Post {"id":1,"title":"商品A","created_at":"2026-11-02 10:00:00","type":"item"}
App\Models\Post {"id":1,"title":"記事A","created_at":"2026-11-01 10:00:00","type":"post"}

type が違うので、「お知らせ」も2件とも残りました。

id は posts と items で同じ番号があり得るので、$row->type と $row->id の組で詳細ページを決めます。

世の中の union 記事、クエリビルダばかりしか引っかからないけど、Eloquent でもいけます。

Eloquent でもいけます。

なんやかんやリレーションが優秀なので、お世話になりたいですよね。

クエリビルダ(DB::table())で書いた場合も、Laravel 13 で同じ SQL になりました。

$items = DB::table('items')->select('title', 'created_at');
$results = DB::table('posts')->select('title', 'created_at')
    ->union($items)
    ->get();

違いは結果の型で、クエリビルダは stdClass のオブジェクト、Eloquent は Post のモデルで返ってきました。

元となるテーブルのセレクトしたカラムの順番になる

union も万能ではありません。

元となるテーブルでセレクトしたカラムの順番になります。

そのため、union で入れたテーブルもそのカラムの順番で良いような select をしてあげる必要があります。

Laravel 13 で、items 側だけ select('created_at', 'title') と逆にしてみると、エラーにはならず、値が入れ替わったまま返ってきました。

(select `title`, `created_at` from `posts`) union (select `created_at`, `title` from `items`)

App\Models\Post {"title":"記事A","created_at":"2026-11-01 10:00:00"}
App\Models\Post {"title":null,"created_at":"2026-11-03 10:00:00"}
App\Models\Post {"title":"お知らせ","created_at":"2026-11-05 10:00:00"}
App\Models\Post {"title":"2026-11-02 10:00:00","created_at":"商品A"}
App\Models\Post {"title":"2026-11-04 10:00:00","created_at":null}
App\Models\Post {"title":"2026-11-05 10:00:00","created_at":"お知らせ"}

カラム名ではなく、select に書いた順番で合わせられています。

エラーが出ないぶん気づきにくいので、select の並びはそろえておきましょう。

select でカラム数を合わせる必要がある

前述の特性があるため、union はカラム数を元となるテーブルに合わせる必要があります。

もし、もとのカラム数と違う数 select してしまった場合、

SQLSTATE[21000]: Cardinality violation: 1222 The used SELECT statements have a different number of columns (SQL: (select `title`, `created_at` from `posts` where `title` is not null) union (select `title` from `items`))

このようなエラーになります。

Laravel 13・MySQL 8.4 でも同じエラーになり、メッセージの後半に接続先が入る形になっていました。

SQLSTATE[21000]: Cardinality violation: 1222 The used SELECT statements have a different number of columns (Connection: mysql, Host: mysql, Port: 3306, Database: laravel, SQL: (select `title`, `created_at` from `posts` where `title` is not null) union (select `title` from `items`))

片方のテーブルにないカラムは、DB::raw('NULL as price') のように null を返すカラムを足すと、数をそろえられます。

items の price を posts の行にも出したい場合で確かめました。

$posts = Post::select('title', 'created_at', DB::raw('NULL as price'));
$results = Item::select('title', 'created_at', 'price')
    ->union($posts)
    ->orderBy('created_at')
    ->get();
(select `title`, `created_at`, `price` from `items`) union (select `title`, `created_at`, NULL as price from `posts`) order by `created_at` asc

App\Models\Item {"title":"記事A","created_at":"2026-11-01 10:00:00","price":null}
App\Models\Item {"title":"商品A","created_at":"2026-11-02 10:00:00","price":1000}
App\Models\Item {"title":null,"created_at":"2026-11-03 10:00:00","price":null}
App\Models\Item {"title":null,"created_at":"2026-11-04 10:00:00","price":500}
App\Models\Item {"title":"お知らせ","created_at":"2026-11-05 10:00:00","price":0}
App\Models\Item {"title":"お知らせ","created_at":"2026-11-05 10:00:00","price":null}

エラーにならず、posts の行は price が null になりました。

今度は Item から始めたので、結果はすべて App\Models\Item のモデルです。

まとめ

以上です。

Laravel で Union を使う方法を記事にしました。

where はそれぞれのクエリに書く、orderBy は union の後ろに書く、select のカラムは数と順番をそろえる、の3つを押さえておけば、違うテーブル同士を1つの一覧にできます。

誰かの参考になればと思います。

フィードバックのお願い
この記事のフィードバックがありましたらYoutubeの適当な動画にコメントしていただいたり、お問い合わせからご連絡ください。