2012-09-04 1 views
4

안녕하세요, 저는 cakephp에서 사이트를 개발하고 있습니다. 내가 두 개의 테이블이 있습니다 성분 재산권cakephp HABTM association

을 테이블 간의 관계는 hasAndBelongsToMany의 (HABTM)입니다. 나는이 모드에서 시도 새로운 속성 추가해야 내 IngredientController 속으로

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'; 

} 

: 새로운 레코드를 삽입 데이터베이스에

$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 (조인 테이블)에 레코드를 삽입 한 재료 간의 관계, 어떻게 할 수 있습니까? 이 모드에서는 성분 hasMany Properties와 같지만 정확하지 않습니다. 어떻게 해결할 수 있습니까? 또는 materials_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

'ingredients'와'properties' 테이블이 다른 데이터베이스에 있다면, 조인 테이블이 어느 데이터베이스에 있는지가 중요합니까? 조인 테이블의 위치를 ​​지정하거나 두 데이터베이스를 모두 점검 할 수있을만큼 똑똑한 방법은 무엇입니까? – Scott

+0

다른 데이터베이스에 테이블이 있으면이 관계를 수동으로 만들어야한다고 생각합니다. 그것에 관한이 기사를 읽으십시오 : http://www.sanisoft.com/blog/2011/04/04/cakephp-how-to-sav-habtm-data-with-tables-in-different-databases/ @Scott –