2013-11-21 24 views
2

我想做兩件事之一,使用模型中的虛擬字段作爲我的連接模型中的顯示字段,或者使用虛擬字段作爲顯示在find('list' )在我的連接模型上。CakePHP加入virtualField作爲displayField

下面是當前佈局:

模型

<?php 
class Participant extends AppModel { 
    public $hasMany = array('Registration'); 

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

    public $displayField = 'full_name'; 
} 
----- 
class Contest extends AppModel { 
    public $hasMany = array('Registration'); 

} 
----- 
class Registration extends AppModel { 
    public $belongsTo = array('Participant', 'Contest'); 
    public $hasMany = array('Assignment'); 

} 
?> 

表如下:

participants   contests  registrations 
------------   ---------  -------------- 
id     id    id 
first_name   name   contest_id 
last_name       participant_id 

在我的比賽控制器我試圖建立一個列表被視爲複選框在視圖中。

這裏是我的比賽控制器摘錄:

$this->loadModel('Registration'); 
     $this->set('registrations', $this->Registration->find(
       'list', 
         array(
          'conditions' => array('contest_id' => $contestId), 
          'recursive' => 1 
         ) 
      ) 
     ); 
//$contestId is defined previously, and I have verified such. 

這一切實際上運行正常,因爲它是,並且在視圖中會顯示一個複選框列與registration_id爲旁邊的複選框的標籤。

我想獲得一個full_name,如參與者模型中定義的那樣,它是註冊模型的顯示字段。我一直在尋找,似乎無法找到一個好方法。我希望我已經足夠描述了,如果您有任何問題,請告訴我,我會盡力解釋。謝謝。

編輯:我正在使用CakePHP 2.4。

回答

1

嘗試添加「域」參數

$this->loadModel('Registration'); 
$this->set('registrations', $this->Registration->find(
    'list', 
    array(
     'fields' => array('Registration.id', 'Participant.full_name'), 
     'conditions' => array('contest_id' => $contestId), 
     'recursive' => 1 
    ) 
)); 

編輯:顯然使用find()與「域」選項時,蛋糕不到位關聯模型的虛擬領域。

所以,你必須自己建立自己的陣列,希望您的模型使用中可容納的行爲

$registrations = $this->Registration->find(
    'all', 
    array(
     'contain' => array(
      'Participant' => array('full_name') 
     ), 
     'conditions' => array('contest_id' => $contestId), 
    ) 
); 
$registrations = Hash::combine($registrations, '{n}.Registration.id', '{n}.Participant.full_name'); 
$this->set('registrations', $registrations); 
+0

對不起,我忘了我曾試過了。只是爲了咧嘴笑,我再次嘗試,並得到以下內容:錯誤:SQLSTATE [42S22]:未找到列:1054'字段列表'中的未知列'Participant.full_name'。虛擬字段不是從DB中檢索的,顯然是由於生成的SQL中沒有CONCAT語句。 – jtesta

+0

我用不同的方法編輯 – arilia

+0

那麼,我終於回到了這個問題。首先,這沒有奏效。然後我意識到我無法按照指示行事,並錯過了從「列表」到「全部」的查找。您的更新建議完美運作。感謝您的幫助! – jtesta