2012-02-16 93 views
0

在我的應用程序Quotes belongsTo產品中,該產品又屬於一種材料。由於我無法在查找數組後將產品模型包含在從報價模型訪問的材料中,因此我已將報價直接與材料相關聯。CakePHP - 在beforeSave中訪問相關模型

我現在遇到的問題是,對於報價material_id需要被自動保存在此基礎上選擇了報價

即從所選產品拉動Product.material_id價值的產品和在報價保存到數據庫之前,自動將其保存到Quote.material_id字段。

我對cakePHP很新穎。有誰知道這可以做到嗎?

編輯:

下面是一個幫助解釋的例子。在我的報價模式,我可以有:

public function beforeSave($options) { 
    $this->data['Quote']['material_id'] = 4; 
    return true; 
} 

,但我需要做更多的東西像這樣不工作:

public function beforeSave($options) { 
    $this->data['Quote']['material_id'] = $this->Product['material_id']; 
    return true; 
} 

回答

3

我感到震驚。這並沒有被正確回答卻....

OLDSKOOL的迴應是半正確的,但不完全正確。使用「$ this-> Quote」是不正確的,因爲beforeSave函數本身駐留在Quote類中。我會用一個例子來解釋。

- >我們的模型認購屬於關聯一個SubscriptionsPlan

- >型號SubscriptionsPlan的hasManySuscriptions

要訪問SubscriptionsPlan在數據beforeSave功能訂購型號,你會做以下幾點:

public function beforeSave($options = array()){ 
    $options = array(
     'conditions' => array(
      'SubscriptionsPlan.subscriptions_plan_id' => $this->data[$this->alias]['subscriptions_plan_id'] 
     ) 
    ); 

    $plan = $this->SubscriptionsPlan->find('first', $options); 

    //REST OF BEFORE SAVE CODE GOES HERE 
    return true; 
} 
0

應該可能通過使用發現,而不是工作。

public function beforeSave($options) { 
    // Assuming your Product model is associated with your Quote model 
    $product = $this->Quote->Product->find('first', array(
     'conditions' => array(
      'Product.material_id' => $this->data['Quote']['material_id'] 
     ) 
    )); 
    $this->data['Quote']['material_id'] = $product['material_id']; 
    return true; 
}