3.7.4.2 Saving Related Model Data (HABTM)
Saving models that are associated by hasOne, belongsTo, and hasMany is pretty simple: you just populate the foreign key field with the ID of the associated model. Once that's done, you just call the save() method on the model, and everything gets linked up correctly.
With HABTM, you need to set the ID of the associated model in your data array. We'll build a form that creates a new tag and associates it on the fly with some recipe.
The simplest form might look something like this (we'll assume that $recipe_id is already set to something):
<?php echo $form->create('Tag');?>
<?php echo $form->input(
'Recipe.id',
array('type'=>'hidden', 'value' => $recipe_id)); ?>
<?php echo $form->input('Tag.name'); ?>
<?php echo $form->end('Add Tag'); ?>
<?php echo $form->create('Tag');?><?php echo $form->input('Recipe.id',array('type'=>'hidden', 'value' => $recipe_id)); ?><?php echo $form->input('Tag.name'); ?><?php echo $form->end('Add Tag'); ?>
In this example, you can see the ‘Recipe.id’ hidden field whose value is set to the ID of the recipe we want to link the tag to. The controller action that handles saving this form, is very simple:
function add() {
//Save the association
if ($this->Tag->save($this->data)) {
//do something on success
}
}
function add() {//Save the associationif ($this->Tag->save($this->data)) {//do something on success}}
And just like that, our new Tag is created and associated with a Recipe, whose ID was set in $this->data['Recipe']['id'].
