2012-06-01 32 views
0

我在我的數據庫中有一個名爲merchants的表,在那個表中我有一個名爲merchant_code的字段,並且我想以這樣的方式爲我的字段生成一個8代碼,即前兩個字符包含來自states表的state_name中的前兩個字母,接下來的兩個字符包含城市表中來自city_name的前兩個字母,最後四個字符應包含從ooo1開始的數字。 在增加,我想這個代碼自動添加,並保存在我的數據庫中商戶的時間 我在cakehp初學者,所以請給我簡單回答,會心存感激,如果我找到了解決辦法從cakephp中的數據庫值中生成一個字符串

回答

2

商人模型可能與City模型(作爲belongsTo)相關聯,而模型又與狀態模型(belongsTo同樣)相關聯。您可以爲您的Merchant模型創建afterSave回調並檢查參數$ created。如果它是真的,只需從相關模型中獲取2條記錄並撰寫您的merchant_code。這樣的事情:(考慮到你在城市模式中使用Containable行爲):

public function afterSave($created) { 
    parent::afterSave($created); 
    if ($created) { 
     $this->City->contain('State'); 
     $names = $this->City->find('first', array(
      'conditions' => array(
       'City.id' => $this->data['Merchant']['city_id'] 
      ), 
      'fields' => array(
       'City.city_name', 
       'State.state_name', 
      ) 
     )); 

     if (!empty($names)) { 
      $merchant_code = substr($names['State']['state_name'], 0, 2) 
       . substr($names['City']['city_name'], 0, 2) 
       . sprintf('%1$04d', $this->getLastInsertID()); 
      $this->saveField('merchant_code', $merchant_code); 
     } 
    } 
} 
相關問題