代码之家  ›  专栏  ›  技术社区  ›  bancer

复合唯一索引的验证规则(非主索引)

  •  6
  • bancer  · 技术社区  · 14 年前

    我确信我不是第一个在表中拥有复合唯一键并希望验证它们的人。我不想发明自行车,所以我先问这里。我有几个表,其中“id”列作为主键,另外两列作为唯一的复合键。最好有一个验证规则来检查提交的条目是否唯一,如果不是,则显示一个验证错误。在Cakephp中,可以通过自定义验证规则来完成。我敢肯定已经有人创造了这样的方法。

    理想情况下,它应该是app\ u model.php中的一个方法,可以由不同的模型使用。

    3 回复  |  直到 14 年前
        1
  •  10
  •   Nik Chankov    14 年前

    我正在使用这个函数:

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

    我用这个很多,它的工作正常。

        2
  •  0
  •   Álvaro González    7 年前

    在最近几年发布的CakePHP/2.x版本中, the isUnique rule

    您可以通过提供多个字段来验证一组字段是否唯一 字段和集合 $or false

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

    我不确定该功能可用时的确切版本,但有 a bug 最迟于2014年10月针对2.3和2.4分支机构提出的核心修正案。

        3
  •  -1
  •   Sadikhasan    10 年前

    你可以把它放在app model中,但我的建议是直接将它添加到模型中,方法是将规则与它的 $validate 财产。

    isUnique rule .