LoginSignup
5
4

More than 3 years have passed since last update.

Laravel 2つの異なるテーブルを合わせて、ページネーションをかける

Last updated at Posted at 2019-05-30

Apple・Lemonテーブル

public function test(Request $request)
{
    $subQuery = Apple::from('apples as A')
        ->select('A.id', 'A.name');

    $list = Lemon::from('lemons as L')
        ->select('L.id', 'L.name')
        ->UnionAll($subQuery)
        ->orderBy('name', 'asc')
        ->paginate(10);

    return view('test',
        [
            'paginate' => $list,
        ]
    );
}

unionは、重複を削除します。UnionAllは重複を削除しません。
union allコストについて参考記事

異なるDBを見たい場合

public function test(Request $request)
{
    $subQuery = Apple::from('sample1.apples as A')
        ->select('A.id', 'A.name');

    $list = Lemon::from('sample2.lemons as L')
        ->select('L.id', 'L.name')
        ->UnionAll($subQuery)
        ->orderBy('name', 'asc')
        ->paginate(10);

    return view('test',
        [
            'paginate' => $list,
        ]
    );
}

テーブルの前にDB名.で指定すると別々のDBを見に行ってくれます。

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