CakePHP model->find and IF condition in field

爱⌒轻易说出口 提交于 2020-01-05 08:52:25

问题


I need to construct a cakePHP model query like this:

SELECT `Translate`.`var_name` , IF( prove_cn_sim =1, lang_cn_sim, lang_en )
FROM 'translate` AS `Translate`

I've tried:

$this->find("list", array(
            'fields' => array("var_name","IF(prove_cn_sim = 1, lang_cn_sim, lang_en)"),
        ));

but I got something like this:

SELECT `Translate`.`var_name`, Translate.IF(prove_cn_sim = 1, lang_cn_sim, lang_en) FROM `translate` AS `Translate`

CakePHP add table prefix to IF. do you know any solutions?


回答1:


Try adding a virtual field to your Translate model:

public $virtualFields = array(
    'lang' => 'IF(Translate.prove_cn_sim = 1, Translate.lang_cn_sim, Translate.lang_en)'
);

Then you can always read the correct value from the virtual lang field when using finds on the model. Which would in your case become something like:

$this->find('list', array(
    'fields' => array('var_name', 'lang'),
));


来源:https://stackoverflow.com/questions/15070166/cakephp-model-find-and-if-condition-in-field

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!