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

【Laravel】クエリビルダでlatest()->first()やoldest()->first()と書いてはいけない

Last updated at Posted at 2024-10-06

latestおよびoldestメソッドを使用すると、結果を日付順に簡単に並べ替えできます。デフォルトでは、結果をテーブルのcreated_atカラムによって順序付けします。もしくは、並べ替えるカラム名を渡すこともできます。

latest()->first()oldest()->first()だと、created_atを基準にレコードを見に行ってしまうため、もしバルクインサートしたデータを取得したい場合、意図しないデータを取得してしまう場合があります。

【結論】

latest()oldest()の引数にidを指定でOK

latest('id')->first();
oldest('id')->first();
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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?