1
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,livewire2.0 TipsAdvent Calendar 2022

Day 13

【Laravel】Eagerロード時に脳死でwithせず必要なカラムだけ記述する

Last updated at Posted at 2022-12-12

概要

EloquentのEagerロード、便利ですよね。いつも脳死でHoge::with('huga')->get()
って書いてたんですけど、カラム指定出来るみたいです

使うカラムだけ指定する

DB
ユーザーテーブルと予定テーブル

スクリーンショット 2022-12-05 15.39.46.png
スクリーンショット 2022-12-05 15.41.01.png

予定レコードからユーザー名だけ取得して使用したい場合はwith('user:id,name')と記述します。

リレーションに必要な主キーや外部キーは必ず指定してください。
今回の場合だとidが必ず必要

さんぷる
dd([
    'ビフォー' => Schedule::with('user')->first()->user->getOriginal(),
    'アフター' => Schedule::with('user:id,name')->first()->user->getOriginal()
]);
結果
array:2 [ // app/Http/Livewire/Sample1202.php:21
  "ビフォー" => array:9 [
    "id" => 1
    "name" => "田中太郎"
    "email" => "rau.terry@example.net"
    "email_verified_at" => Illuminate\Support\Carbon @1670220795 {#1393 ▶}
    "password" => "$2y$10$92IXUNpkjO0rOQ5byMi.Ye4oKoEa3Ro9llC/.og/at2.uheWG/igi"
    "remember_token" => "rfxTH8ZLXy"
    "created_at" => Illuminate\Support\Carbon @1670220795 {#1412 ▶}
    "updated_at" => Illuminate\Support\Carbon @1670220795 {#1415 ▶}
    "deleted_at" => null
  ]
  "アフター" => array:2 [
    "id" => 1
    "name" => "田中太郎"
  ]
]

1
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
1
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?