LoginSignup
4
6

More than 5 years have passed since last update.

Laravelでwithしたモデルのwithも取ってくる

Last updated at Posted at 2017-09-17

何がしたかったか

タイトルの通り、withで取得した先のmodelのwithも取得したかったんです。

例を挙げると、

  • ユーザーが記事を投稿する
  • 他のユーザーはその記事に対してコメント出来る

こんな要件があった場合で、対象となるモデルが

  • User
  • Article
  • Comment

だったとします。

そこで、 記事とそれに紐づくコメント情報を取得したい場合、withを使って

Article.php
public function comments()
{
    return $this->hasMany('App\Models\Comment');
}

としておいて、

$article = Article::with('comments');

で取得出来ると思いますが、今回はCommentを書いた人の名前も一緒に取得したかったんです。

前提

Laravel5.5

どうやったか

withで取得した先のwithを取ってきました。

Article.php
public function comments()
{
    return $this->hasMany('App\Comment');
}
Comment.php
public function user()
{
    return $this->belongsTo('App\User');
}

としておいて、

$article = Article::with('comments')
    ->with('comments.user');

で、articleの中にcommentsが入っていて、commentsの中の各commentにuserが入った状態のデータを取得出来ました。

さいごに

今まで単純なものしかwithで取ってくることなかったんですが、これである程度入れ子のデータを取りたくなってもwithで行けるなと安心しました。

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