6
4

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

Laravel ORMで副問合せして順位まで取得する

Last updated at Posted at 2018-05-23

LaravelでDBのデータを順位付けしたいときってありますよね!
僕はありました!

順位取得SQL

まずSQLの準備です。
データの順位は下記のSQLで取得できます。

rank.sql
SELECT id,
       score,
  (SELECT count(score)
   FROM summaries as b
   WHERE a.score < b.score) + 1 as rank
FROM summaries as a
WHERE a.score IS NOT NULL
ORDER BY rank ASC

この副問合せをLaravelのクエリビルダで書き直します。

Laravel副問合せ構文

副問合せはそのままDB::raw()で書くのがいいっぽいです。

DB::table('table')
			->select(
				DB::raw(
					('select文')
				)
			)
			->get();

参考: Laravel - How to make subquery in select statement?

これで準備が整いました。

実際のORM

SummaryRepository.php

public function getRanks()
{
	return DB::table('summaries as a')
		->select(
			'id',
			'score',
			DB::raw(
				"(select count(score) FROM summaries b WHERE a.score < b.score) + 1 as rank"
			)
		)
		->whereNotNull('a.score')
		->orderBy('rank', 'ASC')
	->get();
}

->get()->toSql()に変更して生成されたSQLを確認すると上述のSQL文が発行されていることがわかります。

これでDBから順位付けされたデータが取得できます!めでたし。

6
4
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
6
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?