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 3 years have passed since last update.

【Laravel】モデル::取得したデータをorderbyする方法(一部データ/全データ)

Last updated at Posted at 2020-12-01

例えばそのモデルのデータを取得し、データの投稿時間(created_at)に沿って順番に取得する場合。
laravel6系 /
postsテーブルとusersテーブルがある。(モデルもPostとUserあり。)

パターン1:一部データを取得した場合

これはわりとすぐうまくいった。

//例えばリレーションテーブルの投稿ユーザーのid:5の投稿を見つけ、
//そのユーザーの投稿のみを投稿時間に沿って取得する場合
$hoge = Post::where('user_id',5)//ユーザーid5の投稿を探す
       ->orderBy('created_at','desc')//投稿時間のdesc(降順)で取得
       ->get();

パターン2:全データを取得した場合

これ少しはまりました。all()だとコレクションとして取得するみたいなんですが、
パターン1のように->orderBy('created_at','desc')は効かず
また下記のコメントのような方法もうまくsortされず。
結局下記のように「Post::orderByDesc('created_at')」でうまく行きました。

$hoge = Post::orderByDesc('created_at')->get();

//Post::All()で取得すると、
//Post::All()->sortByDesc('created_at');みたいな方法があるみたいですがなぜかうまくいかず。。

いまいちはっきり原因を掴めてはいないけれど備忘録的に投稿します!

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?