2
4

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】リレーション時に取得するカラムを設定する方法

Posted at

やりたいこと

リレーションしたものを取得するとき
select *と全カラム対象になるのでこれをやめる

前提

UserとPostが存在し、関係はユーザが複数の投稿を保持

public function posts()
{
    return $this->hasMany(Post::class)
}

やりかた1

withで呼び出す際にカラム名を追記する

User::with(['posts:user_id,name'])->get()

000005.JPG

リレーションするための外部キーをセレクトに入れないといけないので注意

やりかた2

withで呼び出す際にクエリビルダを呼び出す

User::with(['posts' => function($query){
    $query->select(['user_id','name']);
}])->get()

クエリスコープも使えるのでもう少しコンパクトにできる。

// Postモデルにスコープ定義
public function scopeDefaultSelect($query)
{
    return $query->addSelect(['user_id','name']);
}

User::with(['posts' => function($query){
    $query->defaultSelect();
}])->get()

where条件なども使えるし、良き

000006.JPG

やりかた3

リレーション時に指定しておく

// Postモデルにスコープ定義
public function scopeDefaultSelect($query)
{
    return $query->addSelect(['user_id','name']);
}

public function posts()
{
    return $this->hasMany(Post::class)->defaultSelect();
}

なにも意識しなくても、defaultSelctが使用されるしaddSelectを使用していれば、
別途ほかのカラムが欲しいときに、やりかた2の方法で追加できる

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?