使用cakePHP 2.x中的虚拟字段

Alb*_*ert 6 php mysql cakephp-2.3

我已阅读文档,并努力了解该怎么做.另外,我已经阅读了有关stackoverflow的问题,并且没有尝试过任何帮助.

我有一个下拉列表,我想列出公司的所有员工.列表应该显示如下:

Name Surname (Job Title)
Run Code Online (Sandbox Code Playgroud)

在我的模型中,我有这段代码:

public $virtualFields = array(
    'fullname' => 'CONCAT(HrEmployee.name, " ", HrEmployee.surname, " (", HrEmployee.jobTitle, ")")'
);
Run Code Online (Sandbox Code Playgroud)

在我的控制器中,我有这个:

$hrEmployees = $this->User->HrEmployee->find('fullname',
    array(
        'fields' => array('HrEmployee.name','HrEmployee.surname','HrEmployee.jobTitle'),
        'order' => array('HrEmployee.name'=>'ASC','HrEmployee.surname'=>'ASC')
));
Run Code Online (Sandbox Code Playgroud)

但我得到这个错误:

Error: SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'AS `User__fullname` FROM `intraweb_db`.`users` AS `User` WHERE `User`.`hr_emp' at line 1
Run Code Online (Sandbox Code Playgroud)

我该改变什么?我可以看到它正在构建查询,但它正在改变它非常糟糕...

有人可以帮忙吗?

Alb*_*ert 4

很酷,所以我修好了它。部分感谢布兰登为我指明了正确的方向。

由于虚拟字段的限制,我不得不采取解决方法。

因此,在我的 HrEmployee 模型中,我这样做了:

public $virtualFields = array(
    'fullname' => 'CONCAT(HrEmployee.name, " ", HrEmployee.surname, " (", HrEmployee.jobTitle, ")")'
);
Run Code Online (Sandbox Code Playgroud)

在我的用户模型中,我将其更改为:

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'];
}
Run Code Online (Sandbox Code Playgroud)

最后,在我的 UsersController 中,我只是做了一些更改:

$hrEmployees = $this->User->HrEmployee->find('list',
    array(
        'fields' => array("id","fullname"),
        'order' => array('HrEmployee.name ASC','HrEmployee.surname ASC')
));
Run Code Online (Sandbox Code Playgroud)