1
2

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のクエリビルダの中にCASE文を使いたい場合の書き方

Last updated at Posted at 2020-09-27

laravel 7.0
PostgreSQL 12.2

下記コードのようにselectRaw()を使うことで、クエリビルダの記述中に生SQL文を使うことが可能です。

例)
Usersテーブルにgender_idというカラムがり、gender_idの値から性別を文字列に変換して取得したいと思った場合の処理。

$result = $users->select('name')
                  ->selectRaw("(CASE gender_id WHEN 0 THEN "男性" WHEN 1 THEN "女性" END) AS gender")
                  ->get();

データとしては下記のようになります。

name gender
山田太郎 男性
山田花子 女性
1
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
1
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?