2
1

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.

CakePHP CASE文をORMで表現する

Last updated at Posted at 2020-12-07

こちらの記事はユアマイスターアドベントカレンダー2020の7日目の記事です。

やりたいこと

  • SQLのSELECT句におけるCASE文を、ORMで表現したい

TL;DR

  • queryオブジェクトを生成
  • addCase()を使用してCASE文作成
    • 第一引数:条件
    • 第二引数:条件に関連した値
      • 最後の値(new IdentifierExpression('SUM(price)'))は、SQLのELSEの値に当たる
    • 第三引数:型
  • CASE文をORMのSELECT句に指定
$query = $this->Products->find();
$case  = $query->newExpr()->addCase(
    [$query->newExpr()->add(['SUM(price) IS NULL'])],
    [0, new IdentifierExpression('SUM(price)')],
    ['integer', 'integer']
);
$query->select(['price' => $case])->all();

SQL

  • ORMで表現したいSQL
SELECT
    CASE
        WHEN SUM(price) IS NULL THEN 0
        ELSE SUM(price)
    END
FROM products;

ORM

  • 上記のSQLをORMで表現
$query = $this->Products->find();
$case  = $query->newExpr()->addCase(
    [$query->newExpr()->add(['SUM(price) IS NULL'])],
    [0, new IdentifierExpression('SUM(price)')],
    ['integer', 'integer']
);
$query->select(['price' => $case])->all();

解説

  • queryオブジェクトを生成
  • addCase()を使用してCASE文作成
    • 第一引数:条件
    • 第二引数:条件に関連した値
      • 最後の値(new IdentifierExpression('SUM(price)'))は、SQLのELSEの値に当たる
    • 第三引数:型
  • CASE文をORMのSELECT句に指定
2
1
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
2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?