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 3 years have passed since last update.

Laravel: with(eager load) Tips

0
Last updated at Posted at 2022-03-02

with

  • リレーションのメソッドをwith()内に書くことでeager loadができる。
User.php
$users = User::with('posts')->get();

// リレーションメソッド
public function posts() {
    return $this->hasMany(Post::class, 'user_id', 'id');
}
  • リレーション先のobjectには動的プロパティとしてアクセスできる。
foreach ($users as $user) {
    $user->posts;
}
  • リレーションのネストや複数記入も可、その場合は一つずつクエリが発行されている。
$users = User::with([
    'posts.tag',
    'address', 
])->get();
select * from `posts` where `posts`.`user_id` in (userids) and `posts`.`deleted_at` is null
select * from `tags` where `tags`.`post_id` in (postids) and `tags`.`deleted_at` is null
-- //
  • 上記でのクエリからもわかるが「deleted_at is null」がデフォルトで指定。
    便利だが、table名のaliasをつけた時に元の名前でdeleted_atを呼び出そうとしてエラーが出る。
    ->回避方法あるのか?
// error
User::from('users as u')->get();
  • 複数に分けても可
$query = User::query();
$query->with('posts');
$query->with('address');
  • カラムを選択できる
    • リレーション関係の外部キーは必須
    • 半角に注意
$users = User::with('posts:user_id,title');

// 半角開けるとエラー
$users = User::with('posts:user_id, title');
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?