LoginSignup
2
2

More than 5 years have passed since last update.

Eloquentのデータ取得について

Posted at

複数の結果を取得

全部:all()

$user_id = 10;
$trips = Trip::all();

条件で絞込:where(whereNameとか)->get()

where('プロパティ名','符号','比較内容')->get()

$trips = Trip::where('account_id', '=', $user_id)->get();

whereName('比較内容')->get()も可

whereとプロパティ名をキャメルケースでつなげる

$trips = Trip::whereName('田中太郎')->get();

 

複数の結果を返すメソッドではforeachが可能

foreach ($trips as $trip) {
    echo $trip->title;

1つの結果を取得

idを使う場合

$trip = Trip::find(10);

それ以外をキーとして使う場合

$trip = Trip::where('account_id', '=', $user_id)->first();

get()でも取ったら結果が1つでも配列になる

$trips = Trip::where('account_id', '=', $user_id)->get();
$trip = $trips[0]; // この手間が増えてめんどう
2
2
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
2