Using virtual fields in cakePHP 2.x

前端 未结 2 1336
一生所求
一生所求 2021-01-05 10:44

I\'ve read through the documentation and struggled to understand what to do. Also, I\'ve read through the questions here on stackoverflow, and nothing that I tried helped.

相关标签:
2条回答
  • 2021-01-05 11:03

    The bottom of the cake document specifies some limits of virtual fields..

    The implementation of virtualFields has a few limitations. First you cannot use virtualFields on associated models for conditions, order, or fields arrays. Doing so will generally result in an SQL error as the fields are not replaced by the ORM. This is because it difficult to estimate the depth at which an associated model might be found.

    http://book.cakephp.org/2.0/en/models/virtual-fields.html#limitations-of-virtualfields

    0 讨论(0)
  • 2021-01-05 11:18

    Cool so I fixed it. Partially thanks to Brandon for pointing me in the right direction.

    Because of the virtual fields limitation, I had to do the workaround.

    So, in my HrEmployee model I did this:

    public $virtualFields = array(
        'fullname' => 'CONCAT(HrEmployee.name, " ", HrEmployee.surname, " (", HrEmployee.jobTitle, ")")'
    );
    

    And in my User model, I changed it to this:

    class User extends AppModel {
    public function __construct($id = false, $table = null, $ds = null) {
        parent::__construct($id, $table, $ds);
        $this->virtualFields['fullname'] = $this->HrEmployee->virtualFields['fullname'];
    }
    

    And lastly, in my UsersController, I just changed it a bit:

    $hrEmployees = $this->User->HrEmployee->find('list',
        array(
            'fields' => array("id","fullname"),
            'order' => array('HrEmployee.name ASC','HrEmployee.surname ASC')
    ));
    
    0 讨论(0)
提交回复
热议问题