In cakePHP's find(), how do I include a constant?

孤街醉人 提交于 2020-01-14 04:43:11

问题


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

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