title: CakePHP: How to efficiently enforce unique join table records
body: <p>I'm using CakePHP 2.x and I frequently run into situations where I want to add records to a join table, but I want to make sure the same "join" record does not already exist.</p>
  
  <p>For concreteness, here's a basic example...</p>
  
  <p>Model: Student hasAndBelongsToMany Course(s)<br>
  Model: Course hasAndBelongsToMany Student(s)<br>
  Join Table = courses_students and has fields "student_id" and "course_id"</p>
  
  <p>Let's say I have a form with a bunch of students that I want to associate with a course. The form submits a bunch of student_id(s) to the controller. Before I add the new records, I need to make sure the records don't already exist (because you can't enroll for the same course twice). This is where things get messy...</p>
  
  <p>Option 1: I sometimes build a deleteAll() for every (possibly) pre-existing record in the join table that has the current course_id and any of the submitted user_id(s). This is efficient, but the downside is that it erases any pre-existing data that may have been stored in other fields, such as the date etc. </p>
  
  <p>Option 2: I sometimes loop over each of the submitted records and do a find() for each (possibly) pre-existing record. This allows me to preserve existing records, but makes a bunch of extra queries to the DB.</p>
  
  <p>These are the two ways I typically handle this situation, but I suspect there is a better way. What is it?</p>