复合唯一索引(非主要)的验证规则 [英] Validation rule for a composite unique index (non-primary)

查看:111
本文介绍了复合唯一索引(非主要)的验证规则的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我相信我不是第一个在表中有复合唯一键并且想要验证它们的人。我不想发明自行车,所以我先问这里。我有几个表有'id'列作为主键和两个其他列作为唯一复合键。最好有一个验证规则来检查提交的条目是否是唯一的,如果没有,则显示验证错误。在Cakephp它可以通过自定义验证规则。我很肯定有人已经创建了这样的方法。

I am sure I am not the first who has composite unique keys in tables and who wants to validate them. I do not want to invent the bicycle so I ask here first. I have several tables that have 'id' columns as primary keys and two other columns as unique composite keys. It would be nice to have a validation rule to check that the submitted entry is unique and display a validation error if it is not. In Cakephp it could be done by a custom validation rule. I am pretty sure somebody has created such method already.

理想情况下,它将是app_model.php中可以被不同模型使用的方法。

Ideally it would be a method in app_model.php that could be used by different models.

推荐答案

我使用的函数:

function checkUnique($data, $fields) {
    if (!is_array($fields)) {
            $fields = array($fields);
        }
        foreach($fields as $key) {
            $tmp[$key] = $this->data[$this->name][$key];
        }
    if (isset($this->data[$this->name][$this->primaryKey]) && $this->data[$this->name][$this->primaryKey] > 0) {
            $tmp[$this->primaryKey." !="] = $this->data[$this->name][$this->primaryKey];
        }
    //return false;
        return $this->isUnique($tmp, false); 
    }

基本用法是:

'field1' => array(
                'checkUnique' => array(
                    'rule' => array('checkUnique', array('field1', 'field2')),
                    'message' => 'This field need to be non-empty and the row need to be unique'
                ),
            ),
'field2' => array(
                'checkUnique' => array(
                    'rule' => array('checkUnique', array('field1', 'field2')),
                    'message' => 'This field need to be non-empty and the row need to be unique'
                ),
            ),

因此,基本上这会在每个字段下显示警告,说它不是唯一的。

So basically this will show the warning under each of the fields saying that it's not unique.

我使用了很多,它工作正常。

I am using this a lot and it's working properly.

这篇关于复合唯一索引(非主要)的验证规则的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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