Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cakephp query with WHEN CASE

Tags:

case

cakephp

I have below query.

$parents = $this->SurveyQuestion->find('all',array('fields' => array( 
                       'SurveyQuestion.id', 
                       '((CASE WHEN SurveyQuestion.tree_label%2="" THEN \'tree_label\' ELSE \'label\' END)) AS plabel' 
                   ),'conditions' => 
                array('`SurveyQuestion`.`id` <>' => $id), 'recursive' => -1));

I want result like below. I want result from tree_label column if it is not NULL else I want result from label column. Above query returns wrong value.. Can anyone please help ?

like image 262
Himanshu Upadhyay Avatar asked Dec 19 '25 09:12

Himanshu Upadhyay


1 Answers

Giving you an similar example, please try like this :

SELECT
COUNT(CASE WHEN published = 'Y' THEN 1 END) AS number_published,
COUNT(CASE WHEN published = 'N' THEN 1 END) AS number_unpublished
FROM articles

$query = $articles->find();
$publishedCase = $query->newExpr()
->addCase(
    $query->newExpr()->add(['published' => 'Y']),
    1,
    'integer'
);

$unpublishedCase = $query->newExpr()
->addCase(
    $query->newExpr()->add(['published' => 'N']),
    1,
    'integer'
);

 $query->select([
'number_published' => $query->func()->count($publishedCase),
'number_unpublished' => $query->func()->count($unpublishedCase)
]);

hope it helps :)

like image 172
Ajit Agarwal Avatar answered Dec 21 '25 11:12

Ajit Agarwal



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!