cakephp模型virtualFields无法通过包含

前端之家收集整理的这篇文章主要介绍了cakephp模型virtualFields无法通过包含前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我有一个名为User的模型,它有一个名为full_name的 Virtual field.当我在find()查询中访问我的模型User时,我可以在我的虚拟字段上设置条件,没有这样的问题:
$user = $this->User->find('first',array(
    'recursive' => -1,'conditions' => array(
        'User.full_name' => 'Bruce Thomas'
    )
));

上面的查询将成功返回名为Bruce Thomas的用户的数据.但是当我尝试通过另一个模型使用我的模型用户时,问题就出现了,如下所示的Containable行为:

$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]

有关我如何能做到这一点的任何帮助吗?谢谢

根据最新的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错误;使用别名可以避免这种情况.

原文链接:https://www.f2er.com/php/240323.html

猜你在找的PHP相关文章