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.
For concreteness, here's a basic example...
Model: Student hasAndBelongsToMany Course(s)
Model: Course hasAndBelongsToMany Student(s)
Join Table = courses_students and has fields "student_id" and "course_id"
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...
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.
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.
These are the two ways I typically handle this situation, but I suspect there is a better way. What is it?