首页 > 解决方案 > Laravel - 独特的请求规则允许重复

问题描述

在 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 和appearance_identity_id 的组合是唯一的。

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

  1. 我该如何解决这个问题?

  2. 另外,我如何写一个更新?

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

谢谢

标签: laravelrules

解决方案


尝试此代码进行更新

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',          
 ];
} 

推荐阅读