I have a script which adds a MANY_MANY relation to a table when a user chooses to mark an object as belonging to a group. At the moment I simply do this in my controller:
$model = new GroupObject(); $model->groupId = $_POST['groupId']; $model->objectId = $_POST['objectId']; $model->save();
This works fine, until a user adds an object and group that are already linked. I then get the error message:
Integrity constraint violation: 1062 Duplicate entry '1-8' for key 'PRIMARY'
I know I can check for an existing relation in the table by running an SQL query before saving a new record, but this will be two SQL queries. Is there any clever way I can 'try' the insert, and if it fails because of duplicates just treat it as successful?