CakePHP 2.1 - 自定义验证规则 - 检查唯一字段值组合 [英] CakePHP 2.1 - Custom Validation Rule - Check for Unique Field Value Combination

查看:199
本文介绍了CakePHP 2.1 - 自定义验证规则 - 检查唯一字段值组合的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有几个列(ip,provider_id),我想要的值的组合总是唯一的。因此,我试图构建一个自定义验证函数。但我有问题抓住二次字段的价值。这是我的代码到目前为止的模型:

I have a couple of columns (ip, provider_id) for which I want combinations of values to always be unique. Therefore, I am trying to build a custom validation function. But I am having issues grabbing on the value of the secondary field. This is my code so far in the model:

public $validate = array(
   'ip' => array(
      'rule' => array('uniqueClick', 'provider_id'),
      'message' => 'The click is not unique.'
    )
);  

public function uniqueClick ($ip, $field) {

   $count = $this->find('count', array('conditions' => array('ip' => $ip, 'provider_id' => $field)));
   // echo $field;
   return $count == 0;

}

所以问题是,当我测试什么值加载到$字段,它只是'provider_id',一个字符串。我希望它会包含'provider_id'字段的值。有人知道如何获取该值(如果需要,还有所有其他辅助模型字段值),并将其发送到自定义验证函数?

So the problem is that when I am testing what value is loaded into $field, it's just 'provider_id', a string. I was hoping it would contain the value of the 'provider_id' field. Does anyone know how to grab that value (and all other secondary model field values if necessary) and send it to the custom validation function?

我在CookBook中的阅读和讨论过类似问题的人似乎建议这个解决方案可以工作,但不幸的是。

My reading in the CookBook and people who've discussed similar problems seemed to suggest this solution would work, but not for me unfortunately.

提前感谢!

推荐答案

蛋糕它应该在那里。

但是,你的provider_id应该在$ this-> data中可用。 ['MyModel'] ['provider_id']

However, your provider_id should be available in $this->data['MyModel']['provider_id']

因此,您应该可以完全忘记第二个参数,并执行:

So you should be able to forget about that second parameter completely, and do:

public function uniqueClick ($ip) {

   $count = $this->find('count', array(
      'conditions' => array(
          'ip' => $ip, 
          'provider_id' => $this->data[$this->alias]['provider_id'])
   ));
   return $count == 0;

}

希望有帮助!

这篇关于CakePHP 2.1 - 自定义验证规则 - 检查唯一字段值组合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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