Validation rule for a composite unique index (non-primary)

这一生的挚爱 提交于 2019-12-04 04:06:35

I am using that function:

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

basically the usage is:

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

In the CakePHP/2.x versions released in the last few years, the isUnique rule optionally accepts several columns:

You can validate that a set of fields are unique by providing multiple fields and set $or to false:

public $validate = array(
    'email' => array(
        'rule' => array('isUnique', array('email', 'username'), false),
        'message' => 'This username & email combination has already been used.'
    )
);

I'm not sure of the exact version when the feature was available but there's a bug fixed in core as late as October 2014 filed against 2.3 and 2.4 branches.

Jason McCreary

You could put it in app model, but my suggestion would just be to add it to the model directly by placing the rule with it's $validate property.

Check out the built in isUnique rule.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!