【问题标题】:CakePHP: Multi-column unique date + id validationCakePHP:多列唯一日期 + id 验证
【发布时间】:2014-03-25 18:42:03
【问题描述】:

表结构

 id, chart_id, date, rate
 Datapoint belongsTo Chart

我正在尝试对chart_id、日期制定唯一的索引验证规则。我已经尝试使用插件进行验证,MultiColumnUniqueness,但它总是返回 true。

编辑:这不是问题。这对于检查多列唯一性是有效的。见下文。 使用 MultiColumnUniqueness 进行模型验证:

 public $actsAs = array('MultiColumnUniqueness.MultiColumnUniqueness' => array(
        'fields' => array('chart_id', 'date'),
        'errMsg' => "This date for this chart has already been used."
));

有没有办法在 CakePHP 中使用日期验证多列唯一索引?

编辑:我的数据数组是以下结构:

 array(
'Datapoint' => array(
    (int) 0 => array(
        'id' => '1055',
        'date' => array(
            'month' => '12',
            'year' => '2012',
            'day' => '01'
        ),
        'active' => '1',
        'num' => '15',
        'days' => '897',
        'chart_id' => '4'
    ),
    (int) 1 => array(
        'id' => '1054',
        'date' => array(
            'month' => '12',
            'year' => '2012',
            'day' => '01'
        ),
        'active' => '1',
        'num' => '4',
        'days' => '768',
        'chart_id' => '4'
    )
 );

已解决:WalkingRed 的解决方案与我使用的插件一样有效,但这不是问题所在。我试图在保存与 $this->Chart->validates() 关联的 saveAssociated 之前进行验证。事实证明,如果您只是验证,则需要通过不同的方法验证多行:

  if ($this->Chart->saveAssociated($this->request->data, array('validate' => 'only'))) {
        // validates
     } else{
        $errors = $this->Chart->invalidFields(); //validation error
     }

【问题讨论】:

    标签: cakephp cakephp-2.0


    【解决方案1】:

    你在模型中添加了类似的东西吗?

    public $validate = array(
        'chart_id' => array(
            'unique_first_last' => array(
                'rule'    => array('checkMultiColumnUnique', array('chart_id', 'date'), false)
                'message' => 'Chart and date must be unique.'
            )
        ),
    ;)
    
    
    public function checkMultiColumnUnique($ignoredData, $fields, $or = true) {
            return $this->isUnique($fields, $or);
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-09-11
      • 1970-01-01
      • 2011-06-19
      相关资源
      最近更新 更多