0
0

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 1 year has passed since last update.

[Laravel Eloquent] with関数で複数テーブルからcolumnを指定して取得(Eager Loading)

Posted at

サンプルコード

例えば、以下のような3つの親子関係テーブルがあった場合。

・grand_fathers(id, name, age, created_at, updated_at)
・fathers(id, grand_father_id, name, age, created_at, updated_at)
・children(id, father_id, name, age, created_at, updated_at)

get-family-data.php

$family = GrandFather::with(['fathers' => function ($fathers_query) {
    $fathers_query->with(['children' => function ($children_query) {
        $children_query->select(['id', 'father_id', 'name', 'age']); //「father_id」は必ず必要!
    }])->select(['id', 'grand_father_id', 'name', 'age']); //「grand_father_id」は必ず必要!
}])
    ->where('id', '1')
    ->get(['id', 'name', 'age']);

これで、各テーブルからcolumnを指定して取得することができます。

調べていろいろ試しましたが、納得のいくものがなかなか見つからず、
たぶんこれが一番キレイじゃないかなー、、?

もっといいやり方があればコメントいただきたいです。

リレーション設定は忘れずに!

もちろんですが、withを使用する前にはModelのリレーション設定が必要なのでお忘れなく!

0
0
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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?