You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.24 14:45:03