就像在 Kohana 3.3 中一样,动态添加规则?

As in Kohana 3.3 add a rule on the fly?

在 Kohana 3.3 中动态添加规则?即在保存模型用户之前,如果满足某个条件,则需要添加规则city_id模型不能为空,试试这个:

if (Arr::get($data, 'val') > 0){
                    ORM::factory('User')->rules(array('city_id, array(array('not_empty'), array('digit'))));
                }

            try {
                $this->user->update_user($data);
            } catch (ORM_Validation_Exception $e) {
                $errors = $e->errors('Validation');
           }

在任何情况下都绕过,即通常它不起作用

首先,你连想用错了:

ORM::factory('User')->rules(array ('city_id, array (array (' not_empty '), array (' digit '))));

至少应该如下:

ORM::factory('User')->rules(array ('city_id => array (array (' not_empty '), array (' digit '))));

不干预代码是不行的,我会解释...

在 ORM 中:

public function rules()
{
    return array ();
}

我们在模型中覆盖了谁。

即使是记录也意味着对模型中已有内容的重新定义。

ORM::factory('User')->rules(array ('city_id => array (array (' not_empty '), array (' digit '))));

但是你都不能添加需要的方法Class ORM:

public function addRules($a2){
    $a1 = $ this->rules();
    return array_merge_recursive ($a1,$a2);
}

然后我们得到以下内容:

ORM::factory('User')->addRules(array ('city_id => array (array (' not_empty '), array (' digit '))));

很酷,但它不起作用,如:

/**
     * Initializes validation rules, and labels
     *
     * @return void
     */
    protected function _validation()
    {
        // Build the validation object with its rules
        $this->_validation = Validation::factory($this->_object)
            ->bind(':model', $this)
            ->bind(':original_values', $this->_original_values)
            ->bind(':changed', $this->_changed);

        foreach ($this->rules() as $field => $rules)
        {
            $this->_validation->rules($field, $rules);
        }

        // Use column names by default for labels
        $columns = array_keys($this->_table_columns);

        // Merge user-defined labels
        $labels = array_merge(array_combine($columns, $columns), $this->labels());

        foreach ($labels as $field => $label)
        {
            $this->_validation->label($field, $label);
        }
    }

它仍然导致rules(),这是模型...

你可以继续思考,但我建议你利用外部验证