Reputation: 35963
Hi I have a site develop in cakephp. I have two tables: Ingredient Property
The relation between the tables is HasAndBelongsToMany(HABTM). This is my model:
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';
}
Into my IngredientController I have to add a new Property I have tried in this mode:
$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');
}
Into the database insert a new record but If I want that is relation between the ingredients with insert a record in ingredients_properties(table of join), how can I do that? In this mode is like Ingredients hasMany Properties but is not correct. How can I solve it? Or I have to create the record into ingredients_properties manually?
Upvotes: 3
Views: 6360
Reputation: 35963
The solution is that:
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
)
);
}
Upvotes: 1
Reputation: 5464
You can take a look at the following link to achieve the same:
http://book.cakephp.org/2.0/en/models/saving-your-data.html#saving-related-model-data-habtm
Upvotes: 1