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


Using virtual fields in cakePHP 2.x

我已经通读了文档,并努力理解该怎么做。另外,我已经通读了有关stackoverflow的问题,我尝试过的任何内容都没有帮助。

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

Name Surname (Job Title)

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

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

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

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

但是我收到此错误:

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

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

谁能帮忙?

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

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

所以,在我的HrEmployee模型中,我做了这个:

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

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

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'];
}

最后,在我的用户控制器中,我只是稍微改变了它:

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

蛋糕文档的底部指定了虚拟字段的一些限制。

virtualFields的实现有一些限制。首先,不能在条件、顺序或字段数组的关联模型上使用 virtualFields。这样做通常会导致SQL错误,因为这些字段不会被ORM替换。这是因为很难估计可能找到关联模型的深度。

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