views:

308

answers:

3

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"

A: 

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.g

$this->Model->query("ALTER TABLE `yourdatebasename`.`yourtablename` DROP INDEX `guid` ,ADD INDEX `guid` ( `guid` )"); 
SpawnCxy
So Pretty much "no solution?"
SeanDowney
I'm afraid to make Mysql say 'i don't care' you have to do that.:)
SpawnCxy
+2  A: 

It'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 the isUnique validation rule to the guid 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 override Model::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)) to check manually before you save. Again, you could override the save method and have it silently return true if the guid is not unique, but be careful with this sort of thing.

deceze
I agree it looks like I need look into other options. For my situation I ended up need to query again anyway so this is perfect (isUnique). I wasn't aware that there was such a function
SeanDowney
A: 

Hi, i have a question about it, how can i get the mysql statement of a "save" in cake?? i need to get it before the save is done, because i want to save all the insert statements in a "bitacora"...

since now, thanks!!

Tao!

Tao Rivera
Please create your own question about this, don't ask in an answer. :)
deceze