复合唯一密钥验证-laravel [英] composite-unique-key-validation - laravel

查看:71
本文介绍了复合唯一密钥验证-laravel的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

似乎无法使用内置验证器,我应该如何在模型中实现此功能?

seems it's not possible with built-in validators, how I should implement this feature in the model?

 $rules = [

            'user_id' => 'required|unique:service_details,user_id',
            'service_id'=>'required|unique:service_details,service_id'
         ];

以上将独立防止user_idservice_id重复,这不是我的要求

above will prevent duplicacy of user_id and service_id independently which is not my requirement

它将拒绝

(1,2)
(1,3)

因为1是重复的,但是应该接受,因为我想要复合唯一键

because 1 is duplicate but it should be accepted as i want composite unique key

推荐答案

复合唯一字段验证是5.0+版本中的现成提供的.我不能说早期版本.

Composite unique field validation is provided out-of-the-box in 5.0+. I can't speak for earlier versions.

从本质上来说,您可以为应用唯一验证规则的时间指定一个where子句.例如

You can essentially specify a where clause for when your unique validation rule applies. E.g.

'term'  => 'unique:terms,term,NULL,id,taxonomy,category'

此规则规定,termterms表上应是唯一的,但仅在taxonomy等于类别"的情况下.

This rule says that term should be unique on the terms table but only where the taxonomy is equal to "category".

例如,它将防止重复新闻"类别,但我仍然可以使用新闻"标签.

For example, it will prevent a "news" category being duplicated but I can still have a "news" tag.

我不知道您的架构,但是在您的情况下,会是这样:

I don't know your schema but in your case it'd be something like this:

$user_id = Request::get('user_id', $default);
$service_id = Request::get('service_id', $default);  
// or another way of specifying the accompanying service/user ID for the where clauses

$rules = [
    'user_id' => 'unique:service_details,user_id,NULL,id,service_id,' . $service_id;
    'service_id' => 'unique:service_details,service_id,NULL,id,user_id,' . $user_id;
];

这篇关于复合唯一密钥验证-laravel的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆