I’m writing an import from CSV and have been able to successfully manually set data fields on a model in code by using the $this->Book->set() function and passing it a hash containing all of the fieldName => value pairings.
How do I create habtm associations in code? All the examples I’ve seen in the documentation are based on the $this->data returned from a form in the view. Because my data is coming from a csv file and not a view I can’t use this!
So in the following example:
// Book habtm Tags
// Tag habtm Books
$this->Book->create();
$this->Book->set(
array(
'author' => 'tolkein',
'title' => 'lord of the rings')
);
$arrayOfTagIds = array(1, 5, 6);
// Do something with $arrayOfTagIds...
$this->Book->save();
How would I associate the $arrayOfTagIds with the Book?
Instead of using
setto add data to the new entity andsaveto save it, usecreateandsaveAll. In the example below, replace theBookTagmodel with the name of the model used in the relationship between books and tags. You’ll also need to changetag_idto match the name of the field that represents the tag’s id.Example: