Cakephp Insert Ignore Feature?

2019-05-07 14:04发布

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"

2条回答
混吃等死
2楼-- · 2019-05-07 14:10

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` )"); 
查看更多
Emotional °昔
3楼-- · 2019-05-07 14:16

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.

查看更多
登录 后发表回答