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

如何在Laravel迁移中创建含点号的SQL Server列名?

解决Laravel迁移创建SQL Server带点号列名的问题

方法一:用DB::raw()强制保留完整列名

Laravel的Schema构建器会把列名里的点号解析成表与列的分隔符,用DB::raw()包裹带点号的列名,就能阻止这种自动解析,让整个字符串作为完整列名被处理。

修改后的迁移代码:

public function up()
{
    Schema::connection('ConnectionName')->create('table', function(Blueprint $table) {
        $table->id();
        $table->boolean('Active');
        // 用DB::raw包裹带点号的列名,避免被拆分
        $table->string(DB::raw('"Table2.Column1"'))->nullable();
        $table->string(DB::raw('"Table2.Column2"'))->nullable();
        $table->string(DB::raw('"Table3.Column1"'))->nullable();
    });
}

方法二:直接执行原生CREATE TABLE语句

如果Schema构建器的处理仍有问题,直接绕过它用原生SQL创建表,能完全控制列名格式,适配SQL Server的标识符规则:

public function up()
{
    DB::connection('ConnectionName')->statement('
        CREATE TABLE [table] (
            [id] bigint identity primary key not null,
            [Active] bit not null,
            [Table2.Column1] nvarchar(255) null,
            [Table2.Column2] nvarchar(255) null,
            [Table3.Column1] nvarchar(255) null
        )
    ');
}

public function down()
{
    Schema::connection('ConnectionName')->dropIfExists('table');
}

SQL Server中用方括号[]包裹含特殊字符的标识符是最稳妥的方式,能确保点号被识别为列名的一部分。

额外提醒

尽量避免在列名中使用点号这类特殊字符——后续用Eloquent模型访问这类列时,需要通过$model->getAttribute('Table2.Column1')这类方式处理,会增加代码复杂度。

内容的提问来源于stack exchange,提问作者Igic

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.21 03:32:36