2013-02-27 31 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.'%"');