Kohana 3.3 ORM验证-当值为空时,唯一值不起作用 [英] Kohana 3.3 ORM Validation - unique value not working when value is empty

查看:91
本文介绍了Kohana 3.3 ORM验证-当值为空时,唯一值不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Model_Page类中,扩展Kohana ORM类,我具有以下规则定义:

In a Model_Page class, extending the Kohana ORM class, I have this rules definition :

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

为简化此处,我将从此函数返回false,因此当我尝试保存/更新页面时,它将永远不会生效:

To simplify here, I will just return false from this function, so it should never validate when I try to save/update a page :

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

这按预期工作,如果 url的值为非空非空字符串.

This works as expected, if the value for url is not NULL or not an empty string.

但是,如果我已经有一个带有空url的页面,并且试图添加一个具有空url的新页面,则即使强制返回false,也会忽略unique_url函数.

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.

这可能是一个错误,但也许我错过了某件事...?在Kohana文档中,对于唯一的示例,他们使用用户名作为示例,但是用户名也具有not_empty规则,该规则不适用于此处.

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.

任何帮助/建议表示赞赏!

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

我有一个方法:

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.

这篇关于Kohana 3.3 ORM验证-当值为空时,唯一值不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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