Wednesday, May 23, 2012

Saving HABTM for existing records in CakePHP 2.1

This is more of a note for me, since I was doing it wrong, and I couldn't find a clear example in the CakePHP manuals.

The scenario is saving a hasAndBelongsToMany (HABTM) relationship for existing records, and requiring a uniqueness constraint on the join table.  The solution is to use saveAssociated(). The array to pass as the data should look something like this.

$data = array(
    'Model' => array('id' => 1),
    'AssociatedModel' => array(
        array('associated_model_id' => 1),
        array('associated_model_id' => 2)

The AssociatedModel is actually the name of the hasAndBelongsToMany relationship found on the Model model, and will represent the actual join table, which will probably be called models_associated_models.

No comments:

Post a Comment