我使用了phalcon框架来构建rest api。.我建立了所有CRUD函数,但是当使用update时,我无法更新记录,因为验证失败,因为电子邮件是唯一的..我想跳过唯一验证来更新此记录。 。 这是我的验证:
class UpdateUserValidation extends Validation
{
public function initialize()
{
$this->add(
'email',
new Uniqueness([
"model" => new Users,
"message" => ": email already exist",
]));
}}
这是我在控制器中的功能:
public function updateAction($id)
{
$validation = new UpdateUserValidation;
$messages = $validation->validate($_POST);
if (count($messages) > 0 ) {
$all_errors = array();
foreach ($messages as $message) {
array_push($all_errors, $message->getMessage());
}
$this->response->setStatusCode(422,'Validation Error');
$this->response->setJsonContent(array('Message' => $all_errors));
return $this->response;
}
请帮忙
Phalcon DevTools(3.4.0)
PHP 7.1
答案 0 :(得分:0)
它的文档记录不是很好,但是如果您使用当前行实例(模型)进行验证,则该记录将被忽略。
// get record
$user = Users::findFirst([
'email = :email:',
'bind' => [
'email' => 'info@test.com',
],
]);
// validation
$this->add('email', new Uniqueness([
'model' => $user,
'message' => ':email already exist',
]));
$messages = $this->validate([
'email' => 'info@test.com',
]);
// success, because added current record
$messages = $this->validate([
'email' => 'existing@email.com',
]);
// fails, a record with this email already exists
// save
if(!$messages) {
$user->save([
'email' => 'info@test.com',
]);
}