2010-02-15 109 views
2

我有一個小問題。我正在製作一個包含標籤和問題的網站。我有一個問題模型,標籤模型,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的問題,所以它只是更新標籤。

但是這是不正確的,因爲這張表中應該有很多相同的問題,因爲它們涉及屬於它們的不同標籤。

那麼,有沒有辦法來防止這種情況?防止更新的保存方法?

謝謝!

回答

3

此行爲不是特定於HABTM關係。您正在調用循環內的save()方法。第一次保存後,將設置一個id值,每個後續保存調用都會看到該id並假定它是更新。在循環中,首先需要調用model->create()來重置可能存在的id值。

從CakePHP的文檔在http://book.cakephp.org/view/75/Saving-Your-Data

當調用保存在一個循環中,不要忘記調用create()。

在你的情況下,它應該是這樣的:

$this->QuestionsTag->create(); 
$this->QuestionsTag->save (array(
         'question_id' => $this->Question->id, 
         'tag_id'  => $tagId 
        )); 
+0

該訣竅。我想我錯過了手冊中的這一部分,將來必須仔細閱讀。 – vanneto 2010-02-15 15:21:33

0

結賬saveAll。您可以撥打$this->Question->saveAll(),並保存您提供的任何關聯數據。請注意,使用HABTM數據,它將對與該question_id相關聯的任何questions_tags執行DELETE,然後對數據中包含的所有tag_id執行INSERT

0

如果您想要確保創建了新條目(INSERT)而不是更新,則可以在保存調用前設置$this->create();。請參閱http://book.cakephp.org/view/75/Saving-Your-Data(在頁面的上半部分):在循環中調用保存時,不要忘記調用create()。

相關問題