id(); $table->foreignId('machine_id')->constrained()->cascadeOnDelete(); $table->string('name', 150); $table->foreignId('machine_counter_id')->nullable()->constrained()->nullOnDelete(); $table->bigInteger('interval_milli')->nullable(); $table->bigInteger('counter_baseline_milli')->default(0); $table->string('period', 10)->nullable(); $table->unsignedSmallInteger('period_count')->default(1); $table->date('starts_on'); $table->unsignedTinyInteger('warning_percent')->default(90); $table->text('instructions')->nullable(); $table->foreignId('stock_item_id')->nullable()->constrained()->restrictOnDelete(); $table->bigInteger('stock_quantity_milli')->nullable(); $table->boolean('is_active')->default(true); $table->timestamps(); }); Schema::create('maintenance_records', function (Blueprint $table) { $table->id(); $table->foreignId('maintenance_item_id')->constrained()->cascadeOnDelete(); $table->timestamp('performed_at'); $table->foreignId('user_id')->constrained()->restrictOnDelete(); $table->bigInteger('counter_reading_milli')->nullable(); $table->text('note')->nullable(); $table->timestamp('cancelled_at')->nullable(); $table->foreignId('cancelled_by')->nullable()->constrained('users')->restrictOnDelete(); $table->timestamps(); $table->index(['maintenance_item_id', 'performed_at']); }); Schema::table('stock_movements', function (Blueprint $table) { $table->foreign('maintenance_record_id', 'stock_movements_maintenance_foreign')->references('id')->on('maintenance_records')->restrictOnDelete(); }); } public function down(): void { // SQLite (tests) cannot drop a foreign key; there the table is dropped by the earlier migration's rollback. if (Schema::getConnection()->getDriverName() !== 'sqlite') { Schema::table('stock_movements', function (Blueprint $table) { $table->dropForeign('stock_movements_maintenance_foreign'); }); } Schema::dropIfExists('maintenance_records'); Schema::dropIfExists('maintenance_items'); } };