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?
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')
));
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));
));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With