【问题标题】:Is there a way to check if a couple of inputs are unique in laravel 5.2?有没有办法检查 laravel 5.2 中的几个输入是否唯一?
【发布时间】:2023-03-24 01:22:01
【问题描述】:

更新

我有一个包含这些列的表格:

- ID
- production_year
- type

如果type 已经存在于表中并且用户想要传递的值,请检查production_year 是否也已经存在,但只有当这些值存在于同一记录中时验证失败。否则让用户存储这条记录。

我正在尝试检查同一记录中几个字段的唯一性...

我已经看过有关条件验证的文档,但我并没有在那里找到答案。

代码

public function rules()
{
    return [
        // I'd like to check the uniqueness of both of them. In the same record
        'production_y' => 'required|unique',
        'fk_type' => 'required|unique',     
    ];
}

有什么想法吗?谢谢!

【问题讨论】:

  • 您想将“input-A”验证到 db 表中的一列,并将“input-B”验证到 db 表中的同一列?
  • 什么不完全有效?如果您将唯一规则放在两者上,它应该可以工作..
  • 我认为这将分别确定两者的唯一性,而他可能想要确定它们是否一起是唯一的。这就像在数据库中为每列创建 2 个唯一键 1 而不是为 2 列创建一个唯一键。
  • 模型很容易,如果你有两个模型,那么你可以在验证中使用 unique:modelName $this->validate($request, [ 'title' => 'unique:posts|unique:files', ]);
  • 是的,但我几乎可以肯定它也可以通过验证,检查 [laravel.io/forum/… 'production_year' => 'required|unique:table_name,production_year,NULL,id,type,'.$type 类似这样的东西

标签: php validation laravel unique


【解决方案1】:

Laravel 5.3 更新:

现在,您可以使用 Rule (\Illuminate\Validation\Rule) 类流畅地生成相同的规则。

NULL,id 不再需要部分字符串方式。参见:

public function rules()
{
    $type = $this->get('fk_type');

    return [
        'production_y' => [
            'required',
            Rule::unique('your_table', 'production_year')->where(function($query) {
                $query->where('type', $type);
            }),
        ],
    ];
}

原答案

目前无法测试,您可以试试:

public function rules()
{
    $type = $this->get('fk_type');

    return [
        'production_y' => "required|unique:your_table,production_year,NULL,id,type,{$type}",
        // ...
    ];
}

说明:

  1. unique:your_table为唯一检查设置表。
  2. ,production_year 这与 production_y 匹配。
  3. ,NULL,id查看所有记录。

    3.1。如果您使用 {$id},id 之类的,它将检查除 {$id} 之外的记录的唯一性,

  4. ,type,{$type},类型应为{$type}

那会产生某种东西。 like(不是确切的查询,只是为了表达想法):

select count(*) from your_table where production_year = $product_y and where type = $type and where id <> null

【讨论】:

  • 让我检查一下。谢谢
  • 哇!这实际上是有效的!你能更好地解释一下这个验证在做什么吗?将来它会派上用场的!
  • 我明白了,现在我开始明白了。 $this->get('fk_type') 正在处理请求,对吗?它正在存储输入中的外键?
  • 是的。 $this 是 Request 类本身。 get 方法来自于 Laravel FormRequest 扩展的 Symfony 的 Request 类。喜欢 Input::get()。
  • 谢谢!你拯救了我的一天!
【解决方案2】:

如果有人来自 laravel 8,我试过了,它成功了!! 对我来说,我需要检查 (category_id,subcategory_id) 的唯一性,这意味着你可以找到 (1,2),(1,3),(2,1),(2,3) 但你找不到类似的一对!

'category' => "required|unique:tickets,category_id,NULL,id,subcategory_id,{$request->input('subcategory')}"

【讨论】:

    猜你喜欢
    • 2020-04-03
    • 2021-07-23
    • 1970-01-01
    • 1970-01-01
    • 2014-10-28
    • 2021-01-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多