【问题标题】:unique form validation based on two fields基于两个字段的唯一表单验证
【发布时间】:2021-11-18 09:48:30
【问题描述】:

我正在为名为@9​​87654321@ 的表创建一条新记录,其中包括数据库中的一些字段(namedepartment_iddescription)。我需要两个字段的唯一组合(namedepartment_id)。如何验证它以创建和更新函数?

在服务请求中:

return [
          'params.name' => 'required|unique:services,name and depatment_id',
       ];

在服务模型中:

public function department()
{
    return $this->belongsTo(Department::class);
}

在部门模型中:

public function services()
{
    return $this->hasMany(Service::class);
}

在路线中:

Route::apiResource('/services', ServiceController::class)->names([
    'store' => 'services_store',
    'update' => 'services_update',
]);

例如:

特定部门有服务时,报错! 如果有name = service1department_id = 1的记录,用户不能再次创建namedepartment_id的相同记录组合!用户允许使用 (name = service1department_id = another_number) 或 (department_id = 1name = another_name) 创建服务,但不允许使用 (name = service1department_id = 1) 创建新记录

【问题讨论】:

  • 您可以添加第二条唯一规则
  • 我需要它们一起是独一无二的......不是每个单独的文件都是独一无二的
  • 我误会了,我以为您希望 params.name 本身在两个数据库字段中是唯一的

标签: laravel validation unique


【解决方案1】:

您可以这样使用unique 规则:

return [
    'params.name' => [
        'required', 
        Rule::unique('services', 'name')
            ->ignore($this->service)
            ->where('department_id', $this->input('params.department_id'))
     ],
];

在这里,您告诉 Laravel 检查 services 表中是否没有现有记录,其中 $this->input('params.name')name$this->input('params.department_id')department_id

->ignore($this->service) 用于确保我们忽略当前服务(如果我们正在更新),因此它不会在验证期间“找到自己”。

$this->service 将是您正在更新的当前实例(如果您正确设置了路由和控制器,这是另一个主题)。

【讨论】:

  • 谢谢.. 但它给了我这个错误! SQLSTATE[42S22]: Column not found: 1054 Unknown column 'field1' in 'where clause' (SQL: select count(*) as aggregate from services where field1 = test and (field1 is null and field2 is null))
  • 这些列只是占位符,您必须将它们替换为您的实际列
  • 我知道..这是我真正的验证:return [ 'params.name' => ['required', Rule::unique('services')->where(function($q){$q->where('name', $this->input('params.name'))->where('department_id', $this->input('params.department_id')); })],];
  • 如果我理解得很好,您需要namedepartment_id 的独特组合。您是否在此请求中更新服务?如果没有,您的请求正文中是否有department_id?我的意思是,如果没有 namedepartment_id 在某些时候,你想要实现的目标是不可能的,所以我想这个问题在这里缺少一些关键信息。你能用所有东西更新它吗?您使用的路线,您发送的表格,理想情况下dd($this->all()); 的输出(在您的rules 方法中)也会很棒。
  • 我正在做一些测试,我正准备用这个解决方案更新我的答案!您也可以缩短它,请参阅更新的答案。祝你有美好的一天!
猜你喜欢
  • 2011-12-31
  • 2015-12-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-12-10
  • 1970-01-01
  • 2017-10-30
  • 1970-01-01
相关资源
最近更新 更多