您好我在cakephp中开发了一个网站。 我有两张桌子: 成分 属性
表之间的关系是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 hasMany Properties但不正确。 我该如何解决? 或者我必须手动将记录创建为ingredients_properties?
答案 0 :(得分:1)
您可以查看以下链接以实现相同目的:
http://book.cakephp.org/2.0/en/models/saving-your-data.html#saving-related-model-data-habtm
答案 1 :(得分:1)
解决方案是:
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
)
);
}