首页 > 解决方案 > Laravel 中的复合唯一验证

问题描述

如何对两列使用复合唯一验证。就像我有两列诊所名称和日期字段一样。例子。诊所, 07-2019 诊所, 08-2019

$this->validate($request, [
'clinicName'=> 'unique:hospital',
'dates'=> 'unique:hospital',
]);

我的目标是使用复合唯一验证。

标签: laravel

解决方案


根据Laravel Docs,您可以通过以下方式定义规则来做到这一点:

添加额外的 Where 子句:

您还可以通过使用 where 方法自定义查询来指定其他查询约束。例如,让我们添加一个验证 account_id 为 1 的约束:

'email' => Rule::unique('users')->where(function ($query) {
    return $query->where('account_id', 1); 
})

因此,您可以将代码更改为:

$this->validate($request, [
    'clinicName' => Rule::unique('hospital')->where(function ($query) {
        return $query->where('dates', Request::get('dates'));
]);

这将检查您的clinicName位置的唯一性dates是否等于dates您的请求的给定。


推荐阅读