【问题标题】:Unique Keys/Indexes in FuelPHPFuelPHP 中的唯一键/索引
【发布时间】:2012-09-01 22:35:56
【问题描述】:

我目前正在第一次尝试使用 FuelPHP,我想知道如何在模型中标记某些键(例如用户名),以及是否可以使用 oil 来标记。特别是在模型中的验证方面,例如:

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

【问题讨论】:

    标签: php fuelphp


    【解决方案1】:

    如果有一个名为“唯一”的框架定义的验证规则,那就可以了。但是没有。

    文档 (http://docs.fuelphp.com/classes/validation/validation.html#/extending_validation) 中有一个示例说明了如何添加自定义规则,并使用“唯一”作为示例。

    【讨论】:

      【解决方案2】:

      我遇到了一个问题,不包括我正在更新的当前记录。所以为了解决这个问题,我稍微“破解”了它。

      这适用于 Model_Crud,它应该适用于稍加调整的其他人。

      规则(在model/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;
      }
      

      【讨论】:

        猜你喜欢
        • 2011-04-17
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-05-03
        • 2013-09-13
        • 1970-01-01
        • 2010-10-03
        • 1970-01-01
        相关资源
        最近更新 更多