简体   繁体   中英

How to set unique column for specified enum in mysql and laravel?

My table is for time schedule from sunday to satureday ,
i want to make unique key that for sunday time 9 am can be unique but we can use time 9 am for another day in one table,
for example,

day |time
sunday |9.00 am
monday |9.00 am
monday |10.00 am
sunday |9.00 am -> this will be not okay

my migration code is for doctor schedule:-

Schema::create('doctorschedules', function (Blueprint $table) {
            $table->id();
            $table->enum('dayid',["1","2","3","4","5","6","7"]);
            $table->time('starttime');
            $table->time('endtime');
            $table->unsignedBigInteger('dr_id');
            $table->foreign('dr_id')->references('id')->on('doctors');
            $table->timestamps();
        });

dayid is for day Sunday to Saturday

And also main thing is that user will not able to use in between time also like if start time is 9.00 and end time is 10.00 the userwill be not able to take start time 9.30 so please share me logic if have

Example:

 CREATE TABLE test (`day` ENUM('Sun','Mon','Tue','Wed','Fri','Sat'), `time` CHAR(8));
 CREATE UNIQUE INDEX idx ON test ((CASE WHEN `day`='Sun' AND `time`='09:00 am' THEN 0 ELSE NULL END));
 INSERT INTO test VALUES ('Sun', '09:00 am'), ('Sun', '10:00 am'), ('Mon', '09:00 am'), ('Mon', '10:00 am'), ('Mon', '09:00 am'); -- allowed duplicate SELECT * FROM test;
day | time    
:-- |  :------- 
Sun | 09:00 am 
Sun | 10:00 am 
Mon | 09:00 am 
Mon | 10:00 am 
Mon | 09:00 am 
INSERT INTO test VALUES ('Sun', '09:00 am'); -- non-allowed duplicate
Duplicate entry '0' for key 'test.idx'

db<>fiddle here

Map this to Laravel by yourself.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM