Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

cakephp find list

Tags:

cakephp

Hi I want to be able to generate a list using find so that I can use in select helper. but there is a problem. i want too fetch id,name(first + last). so how can I achieve it. I want first_name and last_name to be joined as name . How can I achieve it.

$this->User->find('all',array('fields' => array('first_name','last_name','id')));

I can't use model filters and callback Please suggest me how can I do it in controllers itself.

like image 850
aWebDeveloper Avatar asked Sep 24 '10 09:09

aWebDeveloper


People also ask

How can I get data from cakephp?

To view records of database, we first need to get hold of a table using the TableRegistry class. We can fetch the instance out of registry using get() method. The get() method will take the name of the database table as argument. Now, this new instance is used to find records from database using find() method.

How can I print query in cakephp 2?

Add below code in app_model. php file which is located at root/cake/libs/model. Add below line in your model where you want print query. $last_query = $ this ->ModelName->getLastQuery();


1 Answers

I think this can be done using the virtualFields and displayField properties in your model.

In your model, define a virtual field for the full name like this:

public $virtualFields = array(
    'full_name' => 'CONCAT(User.first_name, " ", User.last_name)'
);

If you now set displayField to full_name you should be able to get a list of your users with the $this->User->find('list') method which you can use without problems with the Form-helper.

public $displayField = 'full_name';

... or:

public $displayField = 'User.full_name';

The id is fetched automatically.

like image 58
Tim Avatar answered Nov 14 '22 04:11

Tim