CakePHPでSQLクリエにCOALESCEを使う

CakePHP#cakephp#COALESCE

この記事は13年以上前に書かれたものです。内容が古くなっている可能性があります。

簡単な事ですがメモ書きです。

CakePHPにてnull値を0として表示したいと思いました。

まーよくある集計ですけど、今回は商品検索みたいな例になります。

さくっと以下のような感じで組んでみました。

price値が100以下(100円以下)の商品を表示といった簡単なものです。

$options = array(
   'conditions' => array(
      'status' => '1',
      'price <=' => '100'
   ),
   'fields' => array(
      'id',
      'name',
      'COALESCE(price, 0)'
   )
);
$this->Model->find('all', $options);

結果は、エラー

いろいろいじった結果以下でいけました。

$options = array(
   'conditions' => array(
      'status' => '1',
      'COALESCE(price, 0) <=' => '100'
   ),
   'fields' => array(
      'id',
      'name',
      'price'
   )
);
$this->Model->find('all', $options);

なるほど。。とよくよく考えるとそうかと思う今日この頃でした(笑)