query function? $this->Model->save(array(" />
开发者

Cakephp Insert Ignore Feature?

Is there a way to do an "insert ignore" in cake without using a model->query function?

            $this->Model->save(array(
                'id'开发者_StackOverflow => 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"


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 (2.x) (3.x) 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)) (2.x) (3.x) 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.


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` )"); 
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜