Drizzle | 使用外键为部分公开的表填充数据
PostgreSQL
MySQL
SQLite
本指南假定您熟悉

示例 1

假设您正尝试使用如下所示的填充脚本和 schema 来填充您的数据库。

index.ts
schema.ts
import { bloodPressure } from './schema.ts';

async function main() {
  const db = drizzle(...);
  await seed(db, { bloodPressure });
}
main();

如果 bloodPressure 表的 userId 列具有非空约束,运行填充脚本将导致错误。

Error: Column 'userId' has not null constraint, 
and you didn't specify a table for foreign key on column 'userId' in 'bloodPressure' table.
这意味着什么?

这意味着由于 userId 列上的非空约束,我们不能用 Null 值填充该列。此外,您没有将 users 表暴露给 seed 函数的 schema,因此我们无法生成 users.id 来用这些值填充 userId 列。

此时,您有以下几种方法来解决此错误:

await seed(db, { bloodPressure, users });

示例 2

index.ts
schema.ts
import { bloodPressure } from './schema.ts';

async function main() {
  const db = drizzle(...);
  await seed(db, { bloodPressure });
}
main();

运行上述填充脚本时,您会看到一个警告。

Column 'userId' in 'bloodPressure' table will be filled with Null values
because you specified neither a table for foreign key on column 'userId' 
nor a function for 'userId' column in refinements.
这意味着什么?

这意味着您既没有将 users 表提供给 seed 函数的 schema,也没有优化 userId 列的生成器。因此,userId 列将被 Null 值填充。

那么您将有两个选择:

优化 userId 列的生成器

这样做要求 users 表在数据库中已经存在诸如 1 和 2 的 ID。

index.ts
import { bloodPressure } from './schema.ts';

async function main() {
  const db = drizzle(...);
  await seed(db, { bloodPressure }).refine((funcs) => ({
    bloodPressure: {
      columns: {
        userId: funcs.valuesFromArray({ values: [1, 2] })
      }
    }
  }));
}
main();