2014-09-24 60 views
1

以及主要問題涉及兩個模型,用戶和MESSAGE,他們有一個關係,因爲什麼消息是做以下事情:如何在具有不同別名的模型中使用virtualFields?

消息可以由用戶發送給其他用戶..所以我必須確定誰是發件人和誰是接收者,並且即時通過設置兩個模型別名爲USER,這是'發件人'和'接收者'(像這樣)。

//This is on User model 
'MessageSender' => array(
     'className' => 'Message', 
     'foreignKey' => 'sender_id' 
    ), 
    'MessageRecipient' => array(
     'className' => 'Message', 
     'foreignKey' => 'recipient_id' 
    ), 

和郵件中的關係是這樣的。

public $belongsTo = array(
    'Recipient' => array(
     'className' => 'User', 
     'foreignKey' => 'recipient_id' 
    ), 
    'Sender' => array(
     'className' => 'User', 
     'foreignKey' => 'sender_id' 
    ) 
); 

了這裏一切都很好..

每當我要創建一個消息我有一個下拉菜單,顯示我的用戶first_names的完整列表,而是因爲我需要知道每個人的姓氏我已經創建了一個$ virtualField來加入它們(first_name和last_name)。

//this is located on the USER model 
public $virtualFields = array(
    'fullname' => 'CONCAT(Recipient.first_name, " ", Recipient.last_name)' 
); 

我如何在創建消息時使用用戶?嗯,我用誰去發送新郵件的發送人,所以發件人是用戶的ID和接收器是在下拉選擇的用戶...

Selecting the Receiver

的主要問題是,當我嘗試訪問引用用戶模型本網站的任何其他部分,它拋出我這個錯誤:

Database Error 
Error: SQLSTATE[42S22]: Column not found: 1054 Unknown column 'Recipient.first_name' in 'field list' 

當然,是因爲我的virtualField期待從「Recipient.first_name結果'和'Recipient.last_name'將它們結合在一起,但是因爲我一直不使用Recivers和Senders ...(因爲那些僅適用於消息模式的使用)它會引發錯誤
我應該如何處理?有沒有什麼辦法可以把任何條件(如果其他人),所以用戶模式將不使用

User.first_name 

,而使用

Receive.first_name 

反之亦然?

如果您需要任何其他信息,請問,我會非常感謝,最好的問候!

+0

你需要這個虛擬現場只有一次或你在你的項目的很多地方使用它? – marian0 2014-09-24 22:29:25

+0

是的,我只需要在項目的這一部分。 – 2014-09-24 22:51:53

回答

2

好的,你可以這樣做兩種方式。首先,你可以快速定義這個虛擬領域,您find()前:

$this->YourModel->virtualFields = array('fullname' => 'CONCAT(Recipient.first_name, " ", Recipient.last_name)'); 
$this->YourModel->find(...); 

或者(如果你有更多的虛擬域)

$this->YourModel->virtualFields['fullname'] = 'CONCAT(Recipient.first_name, " ", Recipient.last_name)'; 
$this->YourModel->find(...); 

第二種方式,這也是未來更靈活,您可以在beforeFind()回調的基礎上在一些開關變量上附加此虛擬字段。因此,在查找查詢之前,您可以激活一個開關,並將該虛擬字段追加到查詢中。

class YourModel extends AppModel { 
    private $_fullNameEnabled = false; 

    public function beforeFind($queryData) { 
     parent::beforeFind($queryData); 

     if (!empty($this->_fullNameEnabled)) { 
      $this->virtualFields = array('fullname' => 'CONCAT(Recipient.first_name, " ", Recipient.last_name)'); 
     } 

     return $queryData; 
    } 

    public function fullnameFieldStatus($status = true) { 
     $this->_fullNameEnabled = $status; 
    } 
} 

然後調用find()使用前:

$this->YourModel->fullnameFieldStatus(); 
2

還有一個第三方式:動態構建虛擬領域,考慮到你的模型被引用作爲別名。

public function __construct($id = false, $table = null, $ds = null) { 
    parent::__construct($id, $table, $ds); 
    $this->virtualFields['fullname'] = sprintf("CONCAT(%s.first_name, ' ', %s.last_name)", 
      , $this->alias, $this->alias); 
} 

利用這種技術,你可以使用:

  • User.fullname
  • Sender.fullname
  • Recipient.fullname
相關問題