Tags

, , ,

An interesting question came up on IRC today, which essentially boils down to:
“How to save extra fields in the join table for HABTM models, while creating a new record for one of the involved models all at once?”

I’ve seen this question float around here and there, but do not recall any specific solutions…

So here, I propose one method which requires a temporary hasMany bind between the model which we are saving and the join table model, then using saveAll() to save the data.

Let’s take a look at an example, where we have the good ol’ Post HABTM Tag.

We are trying to save a new Post, for which we already know a Tag.id (a pretty standard HABTM save scenario), but now we also need to save an extra field ‘status’ into our join table.

//our data array
$this->data['Post']['title'] = 'Hello';
$this->data['Post']['post'] = 'My new post';
$this->data['PostsTag'][0]['tag_id'] = 15;
$this->data['PostsTag'][0]['status'] = 'disabled';

$this->Post->bindModel(array('hasMany'=>array('PostsTag')));
$this->Post->saveAll($this->data);

And that’s all there is to it, we’ve now saved our Post as well as our relation to Tag and the required extra field. Of course, in reality, your data will come from the form, but hopefully you get the gist of this idea.