我有一个FormRequest
,我想在更新行时验证字段fiscal_id
的唯一性,这是一种验证工作,但是问题是fiscal_id
可能为空,因此如果在更新时我发送null,则唯一规则不会通过。
'fiscal_id' => [
'sometimes',
Rule::unique('table', 'fiscal_id')->where(function($query) {
$query->whereNull('deleted_at')
->where('company_id', auth()->user()->company_id);
})->ignore($this->route('customer')->id)
]
当fiscal_id
null
时,如何验证null
的唯一性(因为--Sample data
CREATE TABLE #Login(ID INT IDENTITY, PW nvarchar(20));
INSERT INTO #Login (PW) VALUES
('n9$%^Usj4jjr'),
('Nehj47$%^$'),
('MNAtokay543^A36#$^#%'),
('(*&^#$^dfh$%&'),
('$%^h345nfs54y');
SELECT l.ID, SpecialChars = COUNT(*)
FROM #Login AS l
CROSS APPLY dbo.NGrams8k(l.PW,1) AS ng
WHERE PATINDEX('[^a-zA-Z0-9]',ng.token) = 1
GROUP BY l.ID
HAVING COUNT(*) > 5;
还有其他字段,所以它失败了。)
答案 0 :(得分:0)
尝试像这样单独验证创建和更新
public function rules() {
// rules for updating record
if ($this->method() == 'PATCH') {
return [
'fiscal_id' => [
'nullable',
Rule::unique('table', 'fiscal_id')->where(function($query) {
$query->whereNull('deleted_at')
->where('company_id',auth()->user()->company_id);
})->ignore($this->route('customer')->id)
]
];
} else {
// rules for creating record
return [
'fiscal_id' => [
'required',
Rule::unique('table', 'fiscal_id')->where(function($query) {
$query->whereNull('deleted_at')
->where('company_id',auth()->user()->company_id);
})
]
];
}
}