Romentigo
4 months ago
187
0
Laravel

Unique fields with conditions

Posted 4 months ago by Romentigo

I have the following migration:

PAIRS

public function up()
    {
        Schema::create('pairs', function (Blueprint $table) {
            $table->id();
            $table->bigInteger('classroom_id');
            $table->foreign('classroom_id')
                ->references('id')
                ->on('classrooms')
                ->onDelete('cascade');
            $table->bigInteger('subject_id');
            $table->foreign('subject_id')
                ->references('id')
                ->on('subjects')
                ->onDelete('cascade');
            $table->bigInteger('lecturer_id');
            $table->foreign('lecturer_id')
                ->references('id')
                ->on('lecturers')
                ->onDelete('cascade');
            $table->bigInteger('group_id');
            $table->foreign('group_id')
                ->references('id')
                ->on('groups')
                ->onDelete('cascade');
            $table->bigInteger('day_id');
            $table->foreign('day_id')
                ->references('id')
                ->on('days')
                ->onDelete('cascade');
            $table->bigInteger('week_id');
            $table->foreign('week_id')
                ->references('id')
                ->on('weeks')
                ->onDelete('cascade');
            $table->bigInteger('pair_number_id');
            $table->foreign('pair_number_id')
                ->references('id')
                ->on('pair_numbers')
                ->onDelete('cascade');
            $table->bigInteger('pair_type_id');
            $table->foreign('pair_type_id')
                ->references('id')
                ->on('pair_types')
                ->onDelete('cascade');
            $table->unique(['week_id', 'day_id', 'classroom_id', 'pair_number_id']);
            $table->unique(['group_id', 'day_id', 'pair_number_id', 'week_id']);
            $table->unique(['lecturer_id', 'day_id', 'pair_number_id', 'week_id']);
            $table->timestamps();
        });
    }

Can I use conditions in unique arrays? For example, I have 3 types of a week: every, odd and even. If the classroom is occupied at that time on even weeks, it also can be occupied on odd weeks, even at the same time. But it cannot be occupied on every week. For example:

Week: even - Request: odd - Response: true

Week: every - Request: odd or even - Response: false

Week: even - Request: every - Response: false

So, if it's occupied every week, it cannot be occupied on odd or even week. If it's occupied on even week, it can be occupied also on odd week and vice versa. How can I do this via Laravel migrations? Or should I make it manually in my database?

Please sign in or create an account to participate in this conversation.