2013-02-27 33 views
6

我有一个模型User,它有一个名为full_nameVirtual field。当我进入我的模型User在查找()查询,我可以在我的虚拟字段设置的条件,像这样没有问题:cakephp模型virtualField无法正常工作包含

$user = $this->User->find('first', array(
    'recursive' => -1, 
    'conditions' => array(
     'User.full_name' => 'Bruce Thomas' 
    ) 
)); 

上面的查询将成功返回我的数据叫做布鲁斯·托马斯用户。但问题出现了,当我尝试通过中可容纳的行为像这样通过其他模型中使用我的模型用户:

$user = $this->MyOtherModel->find('first', array(
    'contain' => array('User'), 
    'conditions' => array(
     'MyOtherModel.id' => $my_other_model_id 
     'User.full_name' => 'Bruce Thomas' 
    ) 
)); 

(这个例子上述假设MyOtherModel有我的模型MyOtherModel一个belongsTo关系)

的以上查询给我以下错误:

Warning (512): SQL Error: 1054: Unknown column 'User.full_name' in 'on clause' [CORE\cake\libs\model\datasources\dbo_source.php, line 681]

任何帮助我怎么能做到这一点吗?谢谢

+0

你可以添加/套'配置::写(“调试”,2);'在“应用程序/配置/ core.php“并添加<?php echo $ this-> element('sql_dump');在你的代码中检查查询? – 2013-02-27 21:34:16

+0

你能复制结果吗? – 2013-02-27 21:36:05

回答

10

根据最新的CakePHP的文件(对于V2及以上),这是虚拟域的限制 - this is what it says:这里

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. A common workaround for this implementation issue is to copy virtualFields from one model to another at runtime when you need to access them:

$this->virtualFields['name'] = $this->Author->virtualFields['name']; 

$this->virtualFields += $this->Author->virtualFields; 

更多细节:http://book.cakephp.org/2.0/en/models/virtual-fields.html - 如果您打算实施他们建议的选项(对我来说看起来相当不错),您应该查看“虚拟字段和模型别名”部分以了解避免字段名称冲突(即如果在两个模型中有一个名为full_name的字段,并尝试发出一个同时使用这两个字段的查询,则会出现模糊的字段SQL错误;这是用别名来避免的)。

+0

我没有得到'从一个模型复制virtualFields到另一个'部分。你如何将这个应用到我目前的状况?它似乎并没有工作 – user765368 2013-02-27 22:07:43

+0

没问题,谢谢 – user765368 2013-02-27 22:19:45

+0

似乎你已经得到它,但你会做'$ this-> MyOtherModel-> virtualFields ['full_name'] = $ this-> User-> virtualFields ['full_name']'在发出'find'命令之前。 – 2013-02-27 22:21:14

1

在模型中必须使用下面的代码来创建虚拟领域:

public $virtualFields = array(
    'full_name' => 'CONCAT(YourModelName.first_name, " ", YourModelName.last_name)' 

);

现在,你只需要调用您的控制器的状态数组中下面的代码:

$condition=array($this->YourModelName->virtualFields['your_virtual_field_name'].' LIKE "%'.$YourSearchKeyword.'%"');