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

Laravel 10迁移使用storedAs字段时SQLite报错问题

问题

在全新Laravel 10项目的users迁移文件中添加字段:

$table->integer('test')->nullable()->storedAs('5 * 6');

执行迁移时出现错误:

SQLSTATE[HY000]: General error: 1 near "as": syntax error (Connection: sqlite, SQL: create table "users" ("id" integer primary key autoincrement not null, "name" varchar not null, "email" varchar not null, "email_verified_at" datetime, "password" varchar not null, "remember_token" varchar, "created_at" datetime, "updated_at" datetime, "test" integer as (5 * 6) stored))

但将上述SQL语句直接在SQLite 3.40.1控制台执行可成功。

原因

问题出在Laravel 10的Schema构建器对SQLite存储列的语法支持上:SQLite 3.31.0及以上支持生成列,标准语法是column_name type GENERATED ALWAYS AS (expr) STORED,但Laravel生成的SQL省略了GENERATED ALWAYS关键字。虽然高版本SQLite允许省略该关键字直接执行,但Laravel的SQLite语法解析逻辑没适配这种写法,导致迁移时触发语法错误。

解决方案

1. 用原生SQL执行迁移

直接绕过Schema构建器的语法限制,使用DB::statement执行原生SQL:

新建表场景

如果是创建users表的迁移,替换原Schema代码为:

DB::statement('
    create table "users" (
        "id" integer primary key autoincrement not null,
        "name" varchar not null,
        "email" varchar not null,
        "email_verified_at" datetime,
        "password" varchar not null,
        "remember_token" varchar,
        "created_at" datetime,
        "updated_at" datetime,
        "test" integer as (5 * 6) stored
    )
');

给已有表加字段场景

如果是给已存在的users表添加字段,写alter语句:

DB::statement('alter table "users" add column "test" integer as (5 * 6) stored');

2. 自定义Schema宏(可选,适合多次使用)

如果需要在多个迁移中使用存储列,可以自定义Schema宏来适配SQLite语法:
在App\Providers\AppServiceProvider的boot方法中添加:

use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

Schema::macro('storedColumn', function ($column, $type, $expression) {
    $this->raw("{$column} {$type} as ({$expression}) stored");
});

之后在迁移中就可以这样用:

$table->storedColumn('test', 'integer', '5 * 6')->nullable();

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.27 07:25:07