Note that there are some explanatory texts on larger screens.

plurals
  1. POCakePHP is updating when it should be inserting a HasAndBelongsToMany model
    text
    copied!<p>I have a small problem. I am making a site that has Tags and Questions. I have a Question model, Tag model, QuestionsTag model, everything fits together nicely. The user upon asking something puts the tags in the field seperated by a space (foo bar baz) much like on stackoverflow.com.</p> <p>Now, here is the code to check if a tag already exists or not and entering the tag into the database and the required associations:</p> <pre><code> function create () { if (!empty($this-&gt;data)) { $this-&gt;data['Question']['user_id'] = 1; $question = $this-&gt;Question-&gt;save ($this-&gt;data); /** * Preverimo če se je vprašanje shranilo, če se je, * vprašanje označimo. */ if ($question) { $tags = explode (' ', $this-&gt;data['Question']['tags']); foreach ($tags as $tag){ if (($tagId = $this-&gt;Tag-&gt;existsByName($tag)) != false) { /** * Značka že obstaja, torej samo povezemo trenuten * id z vprašanjem */ $this-&gt;QuestionsTag-&gt;save (array( 'question_id' =&gt; $this-&gt;Question-&gt;id, 'tag_id' =&gt; $tagId )); } else { /** * Značka še ne obstaja, jo ustvarimo! */ $this-&gt;Tag-&gt;save (array( 'name' =&gt; $tag )); // Sedaj pa shranimo $this-&gt;QuestionsTag-&gt;save(array( 'question_id' =&gt; $this-&gt;Question-&gt;id, 'tag_id' =&gt; $this-&gt;Tag-&gt;id )); $this-&gt;Tag-&gt;id = false; } ; } } } } </code></pre> <p>The problem is this, a Question has an id of 1 and I want it to have the tags with id of 1, 2, 3.</p> <p>When the 2nd and 3rd save get called, Cake sees that in the questions_tags table is already a question with id 1, so it just updates the tag.</p> <p>But this is not correct, as there should be many questions in that table with the same id, as they refer to different tags belonging to them.</p> <p>So, is there a way to prevent this? Prevent the save method from UPDATEing?</p> <p>Thank you!</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload