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

- 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',
    ];
}
任何想法?谢谢!

最佳答案

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}",
        // ...
    ];
}

说明:
  • unique:your_table 设置唯一检查表。
  • ,production_year 这与 production_y 匹配。
  • ,NULL,id 检查所有记录。

    3.1.如果您使用 like {$id},id 它将检查唯一性,除了带有 {$id}
  • 的记录
  • ,type,{$type} 类型应该是 {$type}

  • 那会产生……喜欢(不是确切的查询,只是为了表达想法):
    select count(*) from your_table where production_year = $product_y and where type = $type and where id <> null

    关于php - 有没有办法检查laravel 5.2中的几个输入是否唯一?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/38897850/

    10-11 03:16
    查看更多