LoginSignup
0
0

More than 5 years have passed since last update.

Eloquentモデルを取得する際に関連するモデルを紐付ける

Posted at

シングルページアプリケーションを作成していて、一気に関連するデータを取ってきたい場面がありました。

遅延ロード

Eloquentリレーションをプロパティーとしてアクセスする場合、リレーションのデータは「遅延ロード」されます。
つまりプロパティーにアクセスしてはじめて、リレーションのデータがロードされます。

Eagerローディング

Eloquentではモデルを取得した時点でリレーションをロードするようにできる、「Eagerローディング」という機能があります。

$withプロパティをオーバーライドします。

User.php

namespace App;

use Illuminate\Database\Eloquent\Model;

class User extends Model
{

    protected $with = ['books'];

    public function books()
    {
        return $this->hasMany(Book::class);
    }
}

全てのUserを取得します。

App\User::all();
// Userに関連するBookが既に紐付いた状態でUserを取得できる

参考

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