2012-09-04 131 views
4

您好我有一個網站在cakephp開發。 我有兩個表: 成分 屬性cakephp HABTM協會

表之間的關係是HasAndBelongsToMany(HABTM)。 這是我的模型:

class Ingredient extends AppModel { 
    public $name = 'Ingredient'; 
    public $useTable = 'ingredients'; 
    public $belongsTo = 'User'; 

    public $hasAndBelongsToMany = array (
     'Property' => array (
      'className'    => 'Property', 
      'joinTable'    => 'ingredients_properties', 
      'foreignKey'   => 'ingredient_id', 
      'associationForeignKey' => 'property_id', 
      'unique'    => false 
     ) 
    ); 

} 

class Property extends AppModel{ 
     public $name = 'Property'; 
     public $useTable = 'properties'; 

} 

進入我的IngredientController我要添加新的屬性我已經在這種模式下嘗試:

$this->Ingredient->Property->create(); 
       $this->Ingredient->Property->set('user_id',$this->Session->read('Auth.User.id')); 
       $this->Ingredient->Property->set('ingredient_id',$ing['IngredientAlias']['ingredient_id']); 
       if ($this->Ingredient->Property->save($this->request->data)){ 
        $this->set('flash_element','success'); 
        $this->Session->setFlash ('Ingrediente modificato con successo.'); 
        $this->redirect(array('action'=>'edit',$alias)); 
       } 
       else{ 
        $this->set('flash_element','error'); 
        $this->Session->setFlash('Errore di salvataggio activity'); 
       } 

到數據庫中插入一個新的記錄,但如果我想這是在ingredients_properties(連接表)中插入記錄的成分之間的關​​系,我該怎麼做?在這種模式下就像成分有許多屬性,但不正確。 我該如何解決它? 或者我必須手動創建記錄到ingredients_properties中?

回答

2

的解決方案是:

class Ingredient extends AppModel { 
    public $name = 'Ingredient'; 
    public $useTable = 'ingredients'; 
    public $belongsTo = 'User'; 

    public $hasAndBelongsToMany = array (
     'Property' => array (
      'className'    => 'Property', 
      'joinTable'    => 'ingredients_properties', 
      'foreignKey'   => 'ingredient_id', 
      'associationForeignKey' => 'property_id', 
      'unique'    => false 
     ) 
    ); 

} 

class Property extends AppModel{ 
     public $name = 'Property'; 
     public $useTable = 'properties'; 
     public $hasAndBelongsToMany = array (
     'Ingredient' => array (
      'className'    => 'Ingredient', 
      'joinTable'    => 'ingredients_properties', 
      'foreignKey'   => 'property_id', 
      'associationForeignKey' => 'ingredient_id', 
      'unique'    => false 
     ) 
    ); 

} 
+0

如果「成分」和「屬性」表位於不同的數據庫中,那麼連接表所在的數據庫是否有關係?如何指定連接表所在的位置或者是否足夠巧妙地檢查兩個數據庫? – Scott

+0

我認爲如果你在不同數據庫中有表格,你必須手動創建這個關係。閱讀這篇關於它的文章:http://www.sanisoft.com/blog/2011/04/04/cakephp-how-to-sav-habtm-data-with-tables-in-different-databases/ @Scott –