我有一個小問題。我正在製作一個包含標籤和問題的網站。我有一個問題模型,標籤模型,QuestionsTag模型,一切都很好地吻合在一起。用戶在詢問內容時將標籤放在字段中,與空格(foo bar baz)非常相似,就像在stackoverflow.com上一樣。CakePHP正在更新時,它應該插入一個HasAndBelongsToMany模型
現在,這裏是檢查標籤已經存在與否並輸入標籤到數據庫和所需協會代碼:
function create() {
if (!empty($this->data)) {
$this->data['Question']['user_id'] = 1;
$question = $this->Question->save ($this->data);
/**
* Preverimo če se je vprašanje shranilo, če se je,
* vprašanje označimo.
*/
if ($question) {
$tags = explode (' ', $this->data['Question']['tags']);
foreach ($tags as $tag){
if (($tagId = $this->Tag->existsByName($tag)) != false) {
/**
* Značka že obstaja, torej samo povezemo trenuten
* id z vprašanjem
*/
$this->QuestionsTag->save (array(
'question_id' => $this->Question->id,
'tag_id' => $tagId
));
}
else {
/**
* Značka še ne obstaja, jo ustvarimo!
*/
$this->Tag->save (array(
'name' => $tag
));
// Sedaj pa shranimo
$this->QuestionsTag->save(array(
'question_id' => $this->Question->id,
'tag_id' => $this->Tag->id
));
$this->Tag->id = false;
}
; }
}
}
}
問題是這樣的,一個問題有標識1我希望它有ID爲1,2,3的標籤。
當第二次和第三次保存被調用時,Cake看到在questions_tags表中已經有一個id爲1的問題,所以它只是更新標籤。
但是這是不正確的,因爲這張表中應該有很多相同的問題,因爲它們涉及屬於它們的不同標籤。
那麼,有沒有辦法來防止這種情況?防止更新的保存方法?
謝謝!
該訣竅。我想我錯過了手冊中的這一部分,將來必須仔細閱讀。 – vanneto 2010-02-15 15:21:33