AlexBrand
AlexBrand

Reputation: 12429

Virtual field in 'fields' find condition - Cakephp

I have a Student model with a virtual field:

    var $virtualFields = array(
    'full_name' => 'CONCAT(Student.fname, " ", Student.lname)'
);

I am doing a find operation to fetch specific fields using 'fields':

$this->Student->find('all', array('fields' => array('Student.fname','Student.lname')));

For some reason, the virtual field is not being created after finding the records. I tried adding Student.full_name but of course it gives an unknown column error in mysql.

Any ideas?

Upvotes: 2

Views: 15199

Answers (3)

api55
api55

Reputation: 11420

You can't specify in fields a virtual field you need to call it without the fields option so it bring it with the results... you may wanna read the examples in the cookbook

calling all fields is one option another one is to call the field in the fields option, something like this

$this->Student->find('all', array('fields' => array(
    $this->student->virtualFields['full_name'].'AS Student__full_name',
    'Student.fname','Student.lname')
));

Upvotes: 9

Andrés Robert
Andrés Robert

Reputation: 129

On the CookBook: http://book.cakephp.org/2.0/en/models/virtual-fields.html

It says that you can use it like:

Model:

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

Controller or View:

$results = $this->User->find('first');

Result:

array(
    [User] 
        [first_name] => 'Mark',
        [last_name] => 'Story',
        [name] => 'Mark Story',
        //more fields.
    )

So you can use it just like this:

$this->set('list_fields', $this->User->find('list', 
array('fields' => array('first_name', 'last_name', 'name'), 
'recursive' => -1, 'condition' => ...)));

Upvotes: 1

mark
mark

Reputation: 21743

what about placing a method in your app_model.php like so:

/**
 * combine virtual fields with fields values of find()
 * USAGE:
 * $this->Model->find('all', array('fields' => $this->Model->virtualFields('full_name')));
 * @param array $virtualFields to include
 */
public function virtualFields($fields = array()) {
    $res = array();
    foreach ((array)$fields as $field) {
        //TODO: if key numeric => value sql!
        //TODO: allow combined/other models via Model.field syntax
        $sql = $this->virtualFields[$field];
        $res[] = $sql.' AS '.$this->alias.'__'.$field;
    }
    return $res;
}

and then use it like so:

$this->Model->find('all', array('fields' => $this->Model->virtualFields('full_name')))

));

or so:

$fields = $this->Model->virtualFields('full_name');
$fields = am($fields, 'status', 'created');
$this->Model->find('all', array('fields' => $fields));

));

Upvotes: 1

Related Questions