6

我有一个名为的模型,User它有一个名为full_name. 当我在 find() 查询中访问我的模型User时,我可以在我的虚拟字段上设置条件,而不会出现这样的问题:

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

上面的查询将成功地为我返回名为 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有关系)belongsToMyOtherModel

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

警告 (512):SQL 错误:1054:“on 子句”中的未知列“User.full_name”[CORE\cake\libs\model\datasources\dbo_source.php,第 681 行]

请帮助我如何做到这一点?谢谢

4

2 回答 2

10

根据最新的 CakePHP 文档(适用于 v2 及更高版本),这是虚拟字段的限制 -这就是它所说的

virtualFields 的实现有一些限制。首先,您不能在关联模型上将 virtualFields 用于条件、顺序或字段数组。这样做通常会导致 SQL 错误,因为字段不会被 ORM 替换。这是因为很难估计可能找到相关模型的深度。此实现问题的常见解决方法是在运行时将 virtualFields 从一个模型复制到另一个模型,当您需要访问它们时:

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

或者

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

More details here: http://book.cakephp.org/2.0/en/models/virtual-fields.html - if you're planning on implementing the options they suggest (which look quite alright to me) you should take a look at the "Virtual fields and model aliases" section to avoid field name clashes (i.e. if you have a field called full_name in two models and try issuing a query that uses both, you'll get an ambiguous field SQL error; that is avoided with aliases).

于 2013-02-27T21:46:23.723 回答
1

In your model you have to create virtual field using below code :

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

);

Now You simply need to call the below code inside your controller's condition array :

$condition=array($this->YourModelName->virtualFields['your_virtual_field_name'].' LIKE "%'.$YourSearchKeyword.'%"');
于 2015-05-08T07:29:25.570 回答