商人模型可能與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);
}
}
}