2012-02-16 32 views
0

我試圖同時將數據保存到兩個模型(一個模型和相關的hasMany),並且在我的應用程序中的多個位置已經取得了一些成功,但是此方法不會「不像是會與已經強調名稱表/模型來工作,即CakePHP 2.0添加相關數據失敗並丟失數據庫表

//View Code 
echo $this->Form->create('Product'); 
    echo $this->Form->input('name',array('between' => '<br />')); 
    echo $this->Form->input('Component.0.text',array('between' => '<br />')); 
echo $this->Form->end(__('Submit')); 

//Controller Code 
if ($this->Product->saveAssociated($this->request->data)) { 
    $this->Session->setFlash(__('The product has been saved')); 
    $this->redirect(array('action' => 'index')); 
} else { 
    $this->Session->setFlash(__('The product could not be saved. Please, try again.')); 
} 

上述工作正常,但是我有一個模型ProductComponent(db表product_components)

//View Code 
echo $this->Form->create('Product'); 
    echo $this->Form->input('name',array('between' => '<br />')); 
    echo $this->Form->input('ProductComponent.0.text',array('between' => '<br />')); 
echo $this->Form->end(__('Submit')); 

//Controller Code 
if ($this->Product->saveAssociated($this->request->data)) { 
    $this->Session->setFlash(__('The product has been saved')); 
    $this->redirect(array('action' => 'index')); 
} else { 
    $this->Session->setFlash(__('The product could not be saved. Please, try again.')); 
} 

的形式採摘這是正確的,因爲它顯示的是Textarea而不是標準輸入,但是當saveAssociated運行時,我得到響應:

找不到模型ProductComponent的數據庫表product__components。

爲什麼蛋糕要找一張帶有雙下劃線名稱的桌子?

任何想法?

爲Issem丹尼更新:

public $hasMany = array(
    'ProductComponent' => array(
     'className' => 'Product_Component', 
     'foreignKey' => 'product_id', 
     'dependent' => false, 
     'conditions' => '', 
     'fields' => '', 
     'order' => '', 
     'limit' => '', 
     'offset' => '', 
     'exclusive' => '', 
     'finderQuery' => '', 
     'counterQuery' => '' 
    ) 
     ); 
+0

您可以發佈您的模型,以便我們可以看到您的關係設置?我的猜測是那裏出了問題。您是否在您的ProductComponent模型中設置了$ useTable屬性? – 2012-02-16 19:30:54

+0

我認爲你是對的,我剛剛發現我錯誤地輸入了hasMany產品定義中的類名,這將解釋爲什麼它在單獨使用時會起作用。如果你發佈了正確的答案,我會相信你的。 – 2012-02-19 14:25:58

回答

0

有幾件事情:

  • 如果你有THES e三個模型:產品,組件,產品組件,在我看來你試圖設置hasAndBelongsToMany關係。 Check out the cakephp docs.

  • 使用組件作爲或模型中的名字似乎困惑,我..

  • 如果你有一臺product_components模型:你的模型應該被命名爲「ProductComponent」無下劃線(蛋糕將增加自動)。如果你不遵循蛋糕的慣例,你可以聲明「useTable」屬性。您的模型應該是這樣的:

代碼:

// model 

class ProductComponent extends AppModel { 
    public $name = "ProductComponent"; 

    // Only needed when not following cake's conventions 
    public $useTable = "product_components"; 

    // rest of model code ... 
} 

// And the hasmany relation 

public $hasMany = array(
    'ProductComponent' => array(
     'className' => 'ProductComponent', 
     'foreignKey' => 'product_id' 
    ) 
); 

希望幫助,祝你好運。

+0

非常感謝Danny ...第一個例子中的組件只是一個例子來保存複製編碼出另一個控制器,所以不需要HABTM。與hasMany問題雖然點,但謝謝 – 2012-02-19 23:13:36

0

您是否嘗試過使用

$this->Product->saveAll($this->data)) 

嘗試此鏈接SaveAll

+0

嗨亞歷克斯,是的,我用saveAll和saveAssociated,這個問題似乎是在關係某處作爲訪問ProductComponent直接罰款 – 2012-02-19 14:23:07