在cakePHP 2.x中使用虚拟字段 [英] Using virtual fields in cakePHP 2.x

查看:69
本文介绍了在cakePHP 2.x中使用虚拟字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

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

I've got a drop down that I want to list all employees in the company. The list should be displayed like this:

Name Surname (Job Title)

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

In my Model, I have this piece of code:

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

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

And in my controller, I have this:

$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

我必须更改什么?我可以看到它正在构建查询,但它却在改变它,这真是太糟糕了...

What must I change? I can see that it's building the query, but it's changing it horribly bad...

有人可以协助吗?

推荐答案

很酷,所以我修复了它.部分感谢布兰登(Brandon)为我指明了正确的方向.

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.

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

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

最后,在我的UsersController中,我对其进行了一些更改:

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')
));

这篇关于在cakePHP 2.x中使用虚拟字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆