LoginSignup
17
11

More than 5 years have passed since last update.

LaravelのEloquent ORMでCASE式を使う。

Last updated at Posted at 2014-12-17

Laravel4.2のORMを使っていて全面的に生SQLを書きたくなったが、我慢した時のメモ。
結果、部分的にDB:raw()を使うだけです。

コントローラー

app/controllers/UserController.php
<?php
namespace LaravelTest\Controllers;

use Illuminate\Routing\Controller;
use LaravelTest\Models\User;

/**
 * ユーザーコントローラー
 * @package LaravelTest\Controllers
 */
class UserController extends Controller {

  /**
   * ユーザー一覧
   * @return void
   */
  public function getUsers() {
    // ユーザ一覧取得
    $users = User::myPage();
    print_r($users->toArray());// dd($users);
  }
}

モデル

app/models/User.php
<?php
namespace LaravelTest\Models;

use Illuminate\Auth\UserTrait;
use Illuminate\Auth\UserInterface;
use Illuminate\Auth\Reminders\RemindableTrait;
use Illuminate\Auth\Reminders\RemindableInterface;
use Eloquent;
use DB;

/**
 * ユーザーモデル
 * @package LaravelTest\Models
 */
class User extends Eloquent implements UserInterface, RemindableInterface {

    use UserTrait, RemindableTrait;

    /**
     * The database table used by the model.
     *
     * @var string
     */
    protected $table = 'users';

    /**
     * The attributes excluded from the model's JSON form.
     *
     * @var array
     */
    protected $hidden = array('password', 'remember_token');

  // マイページ用の一覧
  public function scopeMyPage($query) {
    return $query->get([
      'name',
      DB::raw("DATE_FORMAT(created_at,'%Y.%m.%d') AS date"),
      DB::raw("(CASE sex WHEN 0 THEN '男性' WHEN 1 THEN '女性' END) AS sex")
    ]);
  }
}

さあみんなで名前空間を書く方のモダンなPHPerになりましょう。

17
11
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
17
11