问题
I'm looking to build a SQL query something like:
"SELECT email.member_id, 1 FROM email ... "
I'm using
$this->Email->find('list', array(
'fields' => array('Email.member_id', '1'), ...
CakePHP is generating:
SELECT `Email`.`member_id`, `Email`.`1` FROM `emails` AS `Email` ...
How do I specify that the 1 is a constant and not a database field?
Why I want to do this
I basically want to return an associative array with keys of member_id and values of 1. Would it be better to just get a straight array of member_ids and then transform that into my wanted data structure? I thought this would be faster.
回答1:
Cake does not easily allow that. In your specific case I would be wondering why you want to have a constant field anyways. But in general do to stuff like that you are supposed to use Virtual Fields:
http://book.cakephp.org/view/1608/Virtual-fields
Basically you would modify model Email by adding this:
var $virtualFields = array(
'one' => '1'
);
Now you can do your query like this:
$this->Email->find('list', array(
'fields' => array('Email.member_id', 'Email.one'), ...
For the usecase you added you should just get a straight array of ids and fill it afterwards. Not only will be that faster, but also less hacky => easier to understand. You can do that easily with ´array_fill_keys()´.
来源:https://stackoverflow.com/questions/7013958/in-cakephps-find-how-do-i-include-a-constant