使用验证保存数据的Cakephp是Unique

时间:2020-12-21 15:16:14

I'm trying to save data with field that has validation isUnique rule but having issue when trying to update via below method.

我正在尝试使用具有验证isUnique规则的字段保存数据,但在尝试通过以下方法更新时遇到问题。

$this->Model->id = 1; 
$this->Model->save($this->data);

If I do above, this generates validation error saying I'm only allowed to have unique value but I'm trying to update this instead.

如果我在上面做,这会生成验证错误,说我只允许具有唯一值但我正在尝试更新它。

Is there a way around this issue?

有没有解决这个问题的方法?

2 个解决方案

#1


2  

That looks ok to me; Cake will attempt to update a record with the primary key of id when it's manually set like that.

这对我来说没问题;当手动设置时,Cake将尝试使用id的主键更新记录。

Do a search in your table with the supposedly "unique" data; and see if any other result can be found. It's possible you have duplicate data that was in use before you introduced the isUnique validation rule.

使用所谓的“唯一”数据在您的表格中进行搜索;并查看是否可以找到任何其他结果。在引入isUnique验证规则之前,您可能会使用正在使用的重复数据。

Are you doing this update within a loop?

你是在循环中做这个更新吗?

You could possibly try changing the on validation rule in your model to create, preventing it from triggering on an update; but I'm not sure that should be necessary; plus you could then update a record with duplicate information, defeating the purpose!

您可以尝试更改模型中的on验证规则以创建,防止它在更新时触发;但我不确定这是否必要;再加上你可以用重复的信息更新一条记录,打败目的!

var $validate = array(
    'fieldName1' => array(
        'rule' => 'isUnique',
        'required' => true,
        'allowEmpty' => false,
        'on' => 'create', // here
        'last' => false,
        'message' => 'Your Error Message'
    )
);

#2


1  

Just pass the id along with the array. Like:

只需将id与数组一起传递即可。喜欢:

$this->create();
$data['id'] = $id;
$this->save($data);

#1


2  

That looks ok to me; Cake will attempt to update a record with the primary key of id when it's manually set like that.

这对我来说没问题;当手动设置时,Cake将尝试使用id的主键更新记录。

Do a search in your table with the supposedly "unique" data; and see if any other result can be found. It's possible you have duplicate data that was in use before you introduced the isUnique validation rule.

使用所谓的“唯一”数据在您的表格中进行搜索;并查看是否可以找到任何其他结果。在引入isUnique验证规则之前,您可能会使用正在使用的重复数据。

Are you doing this update within a loop?

你是在循环中做这个更新吗?

You could possibly try changing the on validation rule in your model to create, preventing it from triggering on an update; but I'm not sure that should be necessary; plus you could then update a record with duplicate information, defeating the purpose!

您可以尝试更改模型中的on验证规则以创建,防止它在更新时触发;但我不确定这是否必要;再加上你可以用重复的信息更新一条记录,打败目的!

var $validate = array(
    'fieldName1' => array(
        'rule' => 'isUnique',
        'required' => true,
        'allowEmpty' => false,
        'on' => 'create', // here
        'last' => false,
        'message' => 'Your Error Message'
    )
);

#2


1  

Just pass the id along with the array. Like:

只需将id与数组一起传递即可。喜欢:

$this->create();
$data['id'] = $id;
$this->save($data);