$virtualFields 和 $belongsto 碰撞,解决方案?

$virtualFields and $belongsto collide, solution?

我还在用cake 2.5.3,但是在更新中找不到相关的东西。我的问题是,belongsto 与另一个模型中的 vitualfields 发生冲突。

首先我为项目做了一个模型:

class Project extends AppModel {
public $belongsTo = array(
    'Responsibleperson' => array(
        'className' => 'User',
        'foreignKey' => 'responsibleperson_id'
    ),
    'Creator' => array(
        'className' => 'User',
        'foreignKey' => 'creator_id'
    ),
);
}

Person responsible 和 person qho create the project 可能不同,但他们都是用户。

这很好用。真的。

后来我在用户模型中添加了以下内容:

public $virtualFields = array(
    'fullname' => 'CONCAT(User.prename, " ", User.name)'
);

现在几乎所有控制器中的 $this->Project->find() 调用都会失败

Column not found: 1054 Unknown column 'User.vorname' in 'field list'

当您查看 mysql 查询时,您会发现查询没有接管更改后的模型名称,它仍在搜索用户...

SELECT 
`Project`.`id`, 
`Project`.`projectname`, 
`Project`.`responsibleperson_id`, 
`Project`.`creator_id`, 
`Responsibleperson`.`id`, 
`Responsibleperson`.`username`, 
`Responsibleperson`.`prename`, 
`Responsibleperson`.`name`, 
(CONCAT(`User`.`prename`, " ", `User`.`name`)) AS `Responsibleperson__fullname`, 
`Creator`.`id`, 
`Creator`.`username`,  
`Creator`.`prename`, 
`Creator`.`name`, 
(CONCAT(`User`.`prename`, " ", `User`.`name`)) AS `Creator__fullname` 
FROM 
`database`.`projects` AS `Project` 
LEFT JOIN 
`database`.`users` AS `Responsibleperson` 
ON 
(`Project`.`responsibleperson_id` = `Responsibleperson`.`id`) 
LEFT JOIN 
`swdevel`.`plantbook_users` AS `Creator` 
ON 
(`Project`.`creator_id` = `Creator`.`id`) 
WHERE 
(`Project`.`projektname` LIKE '%Searchsometing%')

离开虚拟字段中的 "User" 并只写 CONCAT(prename, " ", name),会使它变得模糊。我如何教蛋糕更改虚拟字段的模型名称?

除了在数据库中创建一个具有 "second" 模型的视图之外,是否有任何解决方案?

非常感谢您的帮助。

您需要在 User 构造函数中设置 virtualFields 以处理模型别名:

class User extends AppModel {

    public function __construct($id = false, $table = null, $ds = null) {
        parent::__construct($id, $table, $ds);
        $this->virtualFields['fullname'] = sprintf(
            'CONCAT(%s.prename, " ", %s.name)', $this->alias, $this->alias
        );
    }

}

http://book.cakephp.org/2.0/en/models/virtual-fields.html#virtual-fields-and-model-aliases