我有一个'AddOns'的模型,它有一堆数据。我也有标签,它们以通常的方式工作,只是就像在SO上一样,从逗号分隔的列表中最多允许5个标签。CakePHP - 将两个表手动链接在一起(向HABTM链接表中添加一个字段)
我试图创建的行为如下:
- 用户创建上添加
- 添加上创建
- 系统分裂标记成一个阵列,并通过他们循环
- 系统查找标记,如果存在,我们将使用该ID
- 如果标记不存在,我们将创建它并使用该标识
- 创建一个链接be补间的标签和添加
我可以很容易地使用手动查询,但我不知道这是最好的方法或我应该如何处理这个问题。这里是我的代码:
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
}
您是否阅读了本书中介绍如何保存HABTM数据的部分:http://book.cakephp.org/2.0/en/models/associations-linking-models-together.html#hasandbelongstomany-habtm你有,你有什么尝试? – Dave 2013-05-13 13:34:52
我不确定那是我需要的。我希望在添加主记录('addon')后创建链接,引用标记表中的标记ID(假设有一个)。我将用我想要实现的一些伪代码更新这个问题 – Mike 2013-05-13 17:34:03
@Dave - 我已经添加了伪代码,可能更好地解释我想要实现什么。 – Mike 2013-05-13 17:41:07