gpt4 book ai didi

cakephp 模型 virtualFields 无法通过包含工作

转载 作者:可可西里 更新时间:2023-11-01 13:13:29 26 4
gpt4 key购买 nike

我有一个名为 User 的模型,它有一个 Virtual field名为 full_name。当我在 find() 查询中访问我的模型 User 时,我可以毫无问题地在我的虚拟字段上设置条件,如下所示:

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

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

$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 错误;使用别名可以避免这种情况。

关于cakephp 模型 virtualFields 无法通过包含工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15122506/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com