オタブロ > IT知識 > PHP > 【Laravel】Eloquentとクエリビルダの使い方

【Laravel】Eloquentとクエリビルダの使い方

IT知識
スポンサーリンク

Eloquent

基本書式

User::メソッド名();

getで試してみる

User::get();

実行結果

Illuminate\Database\Eloquent\Collection {#1213 ▼
  #items: array:1 [▼
    0 => App\User {#1214 ▼
      #fillable: array:3 [▶]
      #hidden: array:2 [▶]
      #casts: array:1 [▶]
      #connection: "mysql"
      #table: "users"
      #primaryKey: "id"
      #keyType: "int"
      +incrementing: true
      #with: []
      #withCount: []
      #perPage: 15
      +exists: true
      +wasRecentlyCreated: false
      #attributes: array:8 [▶]
      #original: array:8 [▶]
      #changes: []
      #dates: []
      #dateFormat: null
      #appends: []
      #dispatchesEvents: []
      #observables: []
      #relations: []
      #touches: []
      +timestamps: true
      #visible: []
      #guarded: array:1 [▶]
      #rememberTokenName: "remember_token"
    }
  ]
}

配列で取得したいとき

User::get()->toArray()

実行結果

array:1 [▼
  0 => array:6 [▼
    "id" => 1
    "name" => "test"
    "email" => "test@test.com"
    "email_verified_at" => null
    "created_at" => "2022-03-21 08:41:48"
    "updated_at" => "2022-03-21 08:41:48"
  ]
]

リレーションもできる

$user = User::find(Auth::id());
$user->todos->first()->title

結果

"test"

クエリビルダ

基本書式

DB::table(テーブル名)->メソッド名()

getで試してみる

DB::table('users')->get()

実行結果

Illuminate\Support\Collection {#1204 ▼
  #items: array:1 [▼
    0 => {#1210 ▼
      +"id": 1
      +"name": "test"
      +"email": "test@test.com"
      +"email_verified_at": null
      +"password": "$2y$10$AeD3AswF/dEk2m3Q0KeADezelTK4lWfB1lmy9rqq/7/9.0AIULbrm"
      +"remember_token": null
      +"created_at": "2022-03-21 08:41:48"
      +"updated_at": "2022-03-21 08:41:48"
    }
  ]
}

配列で取得したいとき

DB::table('users')->get()->toArray()

結果

array:1 [▼
  0 => {#1210 ▼
    +"id": 1
    +"name": "test"
    +"email": "test@test.com"
    +"email_verified_at": null
    +"password": "$2y$10$AeD3AswF/dEk2m3Q0KeADezelTK4lWfB1lmy9rqq/7/9.0AIULbrm"
    +"remember_token": null
    +"created_at": "2022-03-21 08:41:48"
    +"updated_at": "2022-03-21 08:41:48"
  }
]
タイトルとURLをコピーしました