Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
521 views
in Technique[技术] by (71.8m points)

php - composite-unique-key-validation - 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'
         ];

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

it will reject

(1,2)
(1,3)

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

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

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

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;
];

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...