Associating CakePHP HABTM models without a view
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 set
to add data to the new entity and save
to save it, use create
and saveAll
. In the example below, replace the BookTag
model with the name of the model used in the relationship between books and tags. You'll also need to change tag_id
to match the name of the field that represents the tag's id.
Example:
$book = array(
'Book' => array(
'author' => 'tolkein',
'title' => 'lord of the rings'
),
'Tag' => array(
'Tag' => array(1,5,6);
)
);
$this->Book->create($book);
$this->Book->saveAll();
精彩评论