Is there a way to do an "insert ignore" in cake without using a model->query function?
$this->Model->save(array(
'id' => NULL,
'guid' => $guid,
'name' => $name,
));
Generates error:
Warning (512): SQL Error: 1062: Duplicate entry 'GUID.....' for key 'unique_guid' [CORE/cake/libs/model/datasources/dbo_source.php, line 524]
It would be great to be able to set some flag or option that says "don't care"
I don't think there's such a simple flag or option in CakePHP since this warning is originally generated by MySql,not cake itself.If you don't need unique feature on
guid
you have to do some index altering query.E.gIt's not really an
INSERT IGNORE
solution, but to handle this situation at the app level you'd use validation rules. If you simply attach theisUnique
validation rule (2.x) (3.x) to theguid
field in your model, Cake will automatically bail out of the save operation if the guid already exists.Behind the scenes it'll make two queries to the database instead of the one that
INSERT IGNORE
would produce, but that shouldn't be a big problem.A problem may be that it'll return
false
for these failed operations and you'll have to use$this->Model->invalidFields()
to figure out what the problem was and if you can ignore it. You could overrideModel::save()
to do this within the model so you don't have to do it every time in the controller.You may also want to use
$this->Model->isUnique(array('guid' => $guid))
(2.x) (3.x) to check manually before you save. Again, you could override thesave
method and have it silently returntrue
if the guid is not unique, but be careful with this sort of thing.