2012-09-01 59 views
2

我目前正在接受我對FuelPHP的第一次冒險,並想知道如何在模型中標記某些鍵(例如用戶名),以及是否可以使用油。特別是在模型驗證方面,如:FuelPHP中的唯一鍵/索引

protected static $_properties = array(
    'id', 
    'name' => array(
    'data_type' => 'string', 
    'label' => 'Name', 
    'validation' => array('required', 'max_length'=>array(100), 'min_length'=>array(10)) //validation rules 
), 
    'username' => array(
    'data_type' => 'string', 
    'label' => 'Username', 
    'validation' => array('required', 'unique') // does this work? 
) 
) 

回答

4

如果有一個框架定義的驗證規則叫做'unique',那就行得通了。但沒有。

在文檔(http://docs.fuelphp.com/classes/validation/validation.html#/extending_validation)中有一個例子,它解釋瞭如何添加自定義規則,並以「unique」爲例。

0

我有一個問題,這不包括我正在更新的當前記錄。所以爲了解決這個問題,我「劈了一下」了一下。

這適用於Model_Crud,它應該與其他適用的人一起工作。

的規則(在模型/ mymodel.php):

protected static $_rules = array(
    'uniqueField' => 'unique[Model_Product,code]', //unique[Model,fieldToCheck] 
); 

所述的方法(在myvalidation.php):

public static function _validation_unique($val, $model, $field) 
{ 
    if (empty($val)) 
    return true; 

    $findOpts = array(
    'where' => array(
     array($field, '=', $val) 
    ) 
); 

    $input = \Validation::active()->input(); 

    if (! empty($input['id'])) 
    $findOpts['where'][] = array('id', '<>', $input['id']); 

    \Validation::active()->set_message('unique', 'The field :label must be unique, but :value has already been used'); 

    //Model_Crud provides a find method which I use to find any of the duplicates 
    $obj = call_user_func(array($model, 'find'), $findOpts); 

    return ! count($obj) > 0; 
}