I have a model for 'AddOns', which has a bunch of data in. I also have tags, which work in the usual manner, just like on SO, allowing a maximum of 5 tags from a comma-separated list.
The behaviour I am trying to create is as follows:
- User creates add on
- Add on is created
- System splits tags up into an array and loops through them
- System looks up tag, if it exists we'll use that ID
- If tag doesn't exist we will create it and use that ID
- Create a link between the tag and the add on
I can do this very easily using a manual query, but I'm not sure that is the best method or how I should approach this. Here is my code:
if ($this->request->is('post')) {
$this->AddOn->create();
$this->AddOn->set('user_id', $this->Auth->user('id'));
if ($this->AddOn->save($this->request->data)) {
// Get the ID of the addon
$addon_id = $this->AddOn->getInsertID();
$tagsarr = explode(',', $this->request->data['Tag']['Tag']);
foreach($tagsarr as $tag){
$tagdb = $this->Tags->findByTagName(trim($tag));
if(!empty($tagdb)){
// HELP! We have a tag, but how do we add the link?
} else {
// Add the tag, but then how do we link it?
}
unset($tagdb);
}
$this->Session->setFlash(
__('The %s has been saved', __('add on'))
);
$this->redirect(array('action' => 'index'));
} else {
$this->Session->setFlash(
__('The %s could not be saved. Please, try again.', __('add on')),
);
}
}
Edit: Added some pseudo code below of what I'm trying to achieve.
$AddOn->create();
$AddOn->save(); // Create AddOn
$AddOnID = $AddOn->insertId(); // Newly inserted AddOn's ID
$tagsArr = explode(',', $post->tags); // Make an array of tags [this,is,a,tag,list]
foreach($tagsArr as $tag){ // Loop through them
$tagFromDb = $Tags->findTagByName($tag); // Try and find the tag from the tags table
if(!$tagFromDb){ // Have we found it? No
$tagId = $Tags->newTag($tag); // Add it and reference
} else { // Have we found it? Yes
$tagId = $tagFromDb->id; // Reference it
}
$AddOnTagsLink->addAddOnTagsLink($AddOnID, $tagId); // Add the link
}