我有一个AddOns'的模型,它有一堆数据。我也有标签,它们以通常的方式工作,就像在SO上一样,允许最多5个标签来自以逗号分隔的列表。
我尝试创建的行为如下:
我可以使用手动查询轻松完成此操作,但我不确定这是最好的方法还是应该如何处理。这是我的代码:
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')),
);
}
}
编辑:在我想要实现的目标之下添加了一些伪代码。
$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
}
答案 0 :(得分:1)
实现这个的逻辑应该是模型,而不是控制器。使用之前的保存回调允许我们在表单中添加“标签”字段并正常保存。
public function beforeSave($options = array()) {
if (isset($this->data['AddOn']['tags'])) {
$this->data['Tag'] = array();
$submitted = array_map('trim', explode(',', $this->data['AddOn']['tags']));
$existing = $this->Tag->find('list', array(
'fields' => array('id', 'name'),
'conditions' => array('name' => $submitted),
'recursive' => -1
));
foreach ($submitted as $tag) {
if(!empty($tag)) {
$id = array_search($tag, $existing);
if (!$id) {
$this->Tag->save(array('name' => $tag));
$id = $this->Tag->id;
}
$this->data['Tag'][] = array('tag_id' => $id);
}
}
}
return true;
}
通过使用一个查询(使用saveAll
)保存所有新标记可以改进该代码,这会将查询数量限制为三个(获取现有,创建缺失,保存)而不是每个新标记一个,但这需要为handling returned IDs做一些额外的工作。如果您的用户经常会创建大量新标签,那么您应该这样做。