简体   繁体   English

Kohana 3.3 ORM验证-值为空时,唯一值不起作用

[英]Kohana 3.3 ORM Validation - unique value not working when value is empty

In a Model_Page class, extending the Kohana ORM class, I have this rules definition : 在Model_Page类中,扩展Kohana ORM类,我具有以下规则定义:

public function rules() {
    return array(
        'url' => array(
            array('Model_Page::unique_url', array($this)),
        ),
    );
}

To simplify here, I will just return false from this function, so it should never validate when I try to save/update a page : 为了简化此处,我将从此函数返回false,因此当我尝试保存/更新页面时,它永远不应验证:

public static function unique_url($page) {
  return false;
}

This works as expected, if the value for url is not NULL or not an empty string . 如果 url的值不是NULL不是一个空字符串 ,这将按预期工作。

But if I already have a page with an empty url, and that I try to add a new page with an empty url, the unique_url function is ignored, even when forcing a return false. 但是,如果我已经有一个具有空url的页面,并且尝试添加一个具有空url的新页面,则即使强制返回false,也会忽略unique_url函数。

This could be a bug, but maybe I missed something...? 这可能是一个错误,但也许我错过了某件事...? In the Kohana docs, for the unique example, they use a username as an example, but the username also has a not_empty rule, which does not apply here. 在Kohana文档中,对于唯一示例,他们使用用户名作为示例,但是用户名也具有not_empty规则,该规则不适用于此处。

Any help/suggestion appreciated! 任何帮助/建议表示赞赏!

I believe the rule is applied once you set the value, not when you're saving it. 我相信规则是在您设置值后才应用,而不是在保存时应用。

I had a similar issue - the filter wasn't working if I didn't assign any value to the field. 我有一个类似的问题-如果我没有为该字段分配任何值,则过滤器将无法正常工作。 I've written my own save method: 我已经编写了自己的保存方法:

public function save(Validation $validation = NULL)
{
    if (!$this->loaded())
    {
        $this->ordering = 0;
    }

    return parent::save($validation);
}

this way the ordering would always be assigned for newly created objects and my filter would work. 这样,将始终为新创建的对象分配顺序,并且我的过滤器将起作用。

And that's how I built another model. 这就是我建立另一个模型的方式。 It's a company model that has a unique company name. 这是一个具有唯一公司名称的公司模型。 Rules for the field are defined like this: 该字段的规则定义如下:

'name' => array(
    array('not_empty'),
    array('max_length', array(':value', 255)),
    array(array($this, 'unique_name'))
)

And I have a method: 我有一个方法:

public function unique_name($value)
{
    $exists = (bool) DB::select(array(DB::expr('COUNT(*)'), 'total_count'))
        ->from($this->_table_name)
        ->where('name', '=', $value)
        ->where($this->_primary_key, '!=', $this->pk())
        ->execute($this->_db)
        ->get('total_count');

    return !$exists;
}

It basically checks if there are any other companies with the same name as the current one. 它基本上检查是否有其他公司与当前公司同名。 Maybe this will give you the idea of what could be wrong with your solution. 也许这会让您想到解决方案可能出了什么问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM