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関数を使ってみる

Posted at

はじめに

リレーションの関係にある親モデルと子モデルのデータを一度に取得したいと考え、with関数にたどり着く。
これまで使ってこなかったのでどのような関数なのか理解するためにまとめていく。

前提(モデル定義)

親モデル(User)と子モデル(UserCourse)は以下のようにリレーション関係にある。

Controller.php
class User extends Model
{
    public function userCourses()
    {
        return $this->hasMany(UserCourse::class);
    }
}

class UserCourse extends Model
{
    public function user()
    {
        return $this->belongsTo(User::class);
    }
}

with関数を使ってみる

with関数を使用して、UserモデルとUserCourseモデルを一度に取得する場合は、以下のように書く。

$users = User::with('userCourses')->get();

これにより、Userモデルのインスタンスが取得され、各UserインスタンスにはuserCoursesリレーションに関連するUserCourseモデルのインスタンスが含まる。

また下記のように1件だけ取ってくるなども可能。

$user = User::with('userCourses')->find($id);

以上。

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?