Laravel-唯一请求规则允许重复

问题描述 投票:2回答:2

在Laravel-5.8中,我对多个字段应用了规则请求,如下所示:

public function rules() 
{
    return [
        'goal_type_id'  => [
            'required',
            Rule::unique('appraisal_goals')->where(function ($query) {
                return $query
                    ->where('employee_id', 1)
                    ->where('appraisal_identity_id', 1);
                })
        ],                  
        'appraisal_doc'  => 'nullable|mimes:doc,docx,xls,xlsx,ppt,pptx,pdf,jpg,jpeg,bmp,png,|max:5000',
        'weighted_score' => 'required|numeric|min:0|max:500',            
    ];
} 

这是mysql查询:

ALTER TABLE appraisal_goals
ADD CONSTRAINT appraisal_goals_uniq1 UNIQUE KEY(goal_type_id,appraisal_identity_id,employee_id);

这是为了创造。在代码中,goal_type_id,employee_id和appraisal_identity_id的组合是唯一的。

当我单击创建刀片中的提交时,它允许重复。

  1. 我该如何解决?

  2. 而且,我该如何写一个用于更新?

[请注意,我的路线是评估目标

谢谢

laravel rules
2个回答
0
投票

尝试此'goal_type_id' => 'required|unique:table_name,filed_name'

public function rules() 
{
    return [
        'goal_type_id'   => [
            'required',
            Rule::unique('appraisal_goals')->where(function ($query) {
                return $query
                    ->where('employee_id', 1)
                    ->where('appraisal_identity_id', 1);
            })
        ],                  
        'appraisal_doc'  => 'nullable|mimes:doc,docx,xls,xlsx,ppt,pptx,pdf,jpg,jpeg,bmp,png,|max:5000',
        'weighted_score' => 'required|numeric|min:0|max:500',            
    ];
}

0
投票

尝试使用此代码进行更新

public function rules() 
{
    $appraisal_goal_id = 'take your appraisal_goals id here from request';
    return [
        'goal_type_id'   => [
            'required',
            Rule::unique('appraisal_goals')->ignore($appraisal_goal_id, 'id')->where(function ($query) {
                return $query
                    ->where('employee_id', 1)
                    ->where('appraisal_identity_id', 1);
            })
        ],
        'appraisal_doc'  => 'nullable|mimes:doc,docx,xls,xlsx,ppt,pptx,pdf,jpg,jpeg,bmp,png,|max:5000',
        'weighted_score' => 'required|numeric|min:0|max:500',          
 ];
} 
© www.soinside.com 2019 - 2024. All rights reserved.