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

Postgres与SQLite环境下AdonisJS种子器ID类型异常问题

AdonisJS SQLite 外键约束失败:UUID 与整数主键不匹配

问题原因

  1. 表结构类型不匹配:roll_table_tags表的roll_table_id被定义为UUID类型(SQLite中映射为CHAR(36)),但关联的roll_tables表主键id在SQLite中被创建为自增整数类型。当种子器尝试将SQLite自动生成的整数1插入到roll_table_tags.roll_table_id字段时,类型不匹配触发外键约束错误。
  2. SQLite自增主键特性:若roll_tables表迁移使用了table.increments('id'),SQLite会将其解析为INTEGER PRIMARY KEY,这类字段会强制自动生成自增整数,完全忽略你手动传入的UUID值,导致created.id返回整数而非预期的UUID。

解决方案

1. 修改roll_tables表迁移,统一主键为UUID

替换自增整数主键为UUID类型,确保所有数据库环境下表结构一致:

// roll_tables 迁移文件
import BaseSchema from '@ioc:Adonis/Lucid/Schema'

export default class extends BaseSchema {
  protected tableName = 'roll_tables'

  public async up() {
    this.schema.createTable(this.tableName, (table) => {
      // 替换 increments('id') 为 UUID 主键
      table.uuid('id').primary()
      table.string('name').unique()
      table.text('description')
      table.timestamp('created_at', { useTz: true })
      table.timestamp('updated_at', { useTz: true })
    })
  }

  public async down() {
    this.schema.dropTable(this.tableName)
  }
}

2. 配置RollTable模型,确保UUID正确处理

明确id字段类型,可添加钩子自动生成UUID(可选,避免种子器漏传):

// app/Models/RollTable.ts
import { BaseModel, column } from '@ioc:Adonis/Lucid/Orm'
import { randomUUID } from 'crypto'
import type { DateTime } from 'luxon'

export default class RollTable extends BaseModel {
  @column({ isPrimary: true })
  public id: string

  @column()
  public name: string

  @column()
  public description: string

  @column.dateTime({ autoCreate: true })
  public createdAt: DateTime

  @column.dateTime({ autoCreate: true, autoUpdate: true })
  public updatedAt: DateTime

  // 可选:创建时自动生成UUID,无需在种子器中手动传入
  public static boot() {
    super.boot()
    this.beforeCreate((model) => {
      model.id = model.id || randomUUID()
    })
  }
}

3. 重新执行迁移与种子器

清理旧表结构并重新初始化数据,确保新表类型生效:

# 回滚所有迁移
node ace migration:rollback --all

# 重新执行迁移
node ace migration:run

# 重新运行种子器
node ace db:seed

额外检查

  • 确认roll_table_tags的迁移中外键关联逻辑正确(当前迁移已配置无误,无需修改)。
  • 若SQLite未开启外键约束,可在config/database.ts的SQLite配置中添加foreignKeys: true。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.27 13:57:51