Cakephp插入忽略功能? [英] Cakephp Insert Ignore Feature?

查看:124
本文介绍了Cakephp插入忽略功能?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法在蛋糕中做插入忽略,而不使用model->查询函数?

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,
            ));

产生错误:

Warning (512): SQL Error: 1062: Duplicate entry 'GUID.....' for key 'unique_guid' [CORE/cake/libs/model/datasources/dbo_source.php, line 524]

这将是很棒的能够设置一些标志或选项,说不关心 / p>

It would be great to be able to set some flag or option that says "don't care"

推荐答案

这不是一个 INSERT IGNORE 解决方案,在应用程序级别,您将使用验证规则。如果您只需附加 isUnique 验证规则( 2.x )( 3.x )到您的模型中的 guid 如果guid已经存在,Cake将自动保存保存操作。

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.

在后台,它会对数据库进行两次查询,而不是 INSERT IGNORE 会产生,但这不应该是一个大问题。

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.

一个问题可能是它会返回 false 这些失败的操作,你必须使用 $ this-> Model-> invalidFields()找出问题是什么,如果你可以忽略它。您可以覆盖 Model :: save()在模型中执行此操作,因此您不必在控制器中每次都这样做。

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.

您还可以使用 $ this-> Model-> isUnique(array('guid'=> $ guid)) 2.x )( 3.x )在保存之前手动检查。同样,您可以覆盖 save 方法,如果guid不是唯一的,则它会静默地返回 true 用这种东西。

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.

这篇关于Cakephp插入忽略功能?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆