Laravel 7使用Migration在SQL Server中设置time(0)失败如何解决?
问题原因
Laravel Schema构建器作为跨数据库的抽象层,对SQL Server的time类型低精度适配存在缺陷,部分版本的SQL Server驱动会忽略time()方法传入的0精度参数,默认生成time(7)类型的字段,导致你设置的time(0)不生效。
解决方法
方案1:使用原生列定义创建字段
直接通过addColumn方法指定完整的类型参数,跳过抽象层的适配逻辑:
$table->id('ID'); // 替换原有time字段定义 $table->addColumn('time', 'Start_Time', [ 'precision' => 0, 'nullable' => false, 'default' => now()->toTimeString() ]); $table->addColumn('time', 'End_Time', [ 'precision' => 0, 'nullable' => false, 'default' => now()->toTimeString() ]); // 其余字段保持原有逻辑不变 $table->string('Des', 255); $table->string('Note')->nullable(); $table->datetime('Time_Created')->nullable(); $table->bigInteger('User_Created')->nullable(); $table->datetime('Time_Updated')->nullable(); $table->bigInteger('User_Updated')->nullable(); $table->boolean('IsDelete')->default(0);
方案2:建表后通过原生SQL强制修改精度
如果方案1未生效,可以在建表逻辑后追加SQL Server原生ALTER语句修改字段类型:
// 原有迁移逻辑不变 $table->id('ID'); $table->time('Start_Time')->default(now()->toTimeString()); $table->time('End_Time')->default(now()->toTimeString()); $table->string('Des', 255); $table->string('Note')->nullable(); $table->datetime('Time_Created')->nullable(); $table->bigInteger('User_Created')->nullable(); $table->datetime('Time_Updated')->nullable(); $table->bigInteger('User_Updated')->nullable(); $table->boolean('IsDelete')->default(0); // 追加修改语句,将代码中的「实际表名」替换为你的表名称 DB::statement('ALTER TABLE 实际表名 ALTER COLUMN Start_Time time(0) NOT NULL'); DB::statement('ALTER TABLE 实际表名 ALTER COLUMN End_Time time(0) NOT NULL');
如果修改后字段默认值丢失,可追加以下语句重置:
DB::statement("ALTER TABLE 实际表名 ADD CONSTRAINT DF_实际表名_Start_Time DEFAULT '".now()->toTimeString()."' FOR Start_Time"); DB::statement("ALTER TABLE 实际表名 ADD CONSTRAINT DF_实际表名_End_Time DEFAULT '".now()->toTimeString()."' FOR End_Time");

内容的提问来源于stack exchange,提问作者Clover Black
相关产品推荐
相关产品推荐

