在我的Laravel5.8项目中,我具有以下用于创建的唯一规则验证代码:
MYSQL
ALTER TABLE `hr_holiday_dates`
ADD UNIQUE KEY `holidaydates_unique_key` ('group_id','holiday_name','date_from');
型号
class HrHolidayDate extends Model
{
protected $table = 'hr_holiday_dates';
protected $primaryKey = 'id';
protected $fillable = [
'holiday_name',
'group_id',
'date_from',
'date_to',
'description',
];
public function holidaygroup()
{
return $this->belongsTo('App\Models\Hr\HrHolidayGroup','group_id');
}
}
控制器
public function edit($id)
{
$userCompany = Auth::user()->company_id;
abort_unless(\Gate::allows('holiday_date_edit'), 403);
$holiday = HrHolidayDate::where('id', $id)->first();
$holidaygroups = HrHolidayGroup::where('company_id', $userCompany)->get();
return view('hr.holiday_dates.edit')->with('holiday', $holiday)->with('holidaygroups', $holidaygroups);
}
public function update(UpdateHolidayDateRequest $request, $id)
{
$dateFrom = Carbon::parse($request->date_from);
$dateTo = Carbon::parse($request->date_to);
$holiday = HrHolidayDate::find($id);
$holiday->holiday_name = $request->holiday_name;
$holiday->group_id = $request->group_id;
$holiday->date_from = $dateFrom;
$holiday->date_to = $dateTo;
$holiday->description = $request->description;
$holiday->save();
Session::flash('success', 'Holiday is updated successfully');
return redirect()->route('hr.holiday_dates.index');
}
规则
'holiday_name' => [
'required',
'min:3',
'max:80',
Rule::unique('holiday_dates')->where(function ($query) {
return $query->where('group_id', $this->group_id)
->where('holiday_name', $this->holiday_name)
->where('date_from', Carbon\Carbon::parse($this->date_from)->format('Y-m-d'));
})
],
正在工作。
假日名称是主要字段,对于group_id和date_from而言是唯一的。 holiday_dates是表名,而holiday_date是路线。
我如何尝试对唯一规则验证进行更新,但是它不起作用:
'holiday_name' =>
[
'required',
'min:3',
'max:80',
Rule::unique('holiday_dates')->where(function ($query) {
return $query
->where('group_id', 1)
->where('holiday_name', 1)
->where('date_from', Carbon\Carbon::parse($this->date_from)->format('Y-m-d'));
})->ignore($this->holiday_date)
],
我该如何解决。
谢谢
答案 0 :(得分:0)
好的。您将id作为主键。因此,当您要更新资源时,将具有模型实例,如下所示。
$hrHolidayDate = HrHolidayDate::find($id); // or any other way to get the model instance.
并如下更新规则。
规则
'holiday_name' =>
[
'required',
'min:3',
'max:80',
Rule::unique('holiday_dates')->where(function ($query) {
return $query
->where('group_id', 1)
->where('holiday_name', 1)
->where('date_from', Carbon\Carbon::parse($this->date_from)->format('Y-m-d'));
})->ignore($hrHolidayDate->id)
]