这意味着由于 userId
列上的非空约束,我们无法用 Null 值填充该列。此外,你没有将 users
表暴露给 seed
函数模式,因此我们无法生成 users.id
来使用这些值填充 userId
列。
Drizzle | 使用外键种子部分公开的表
PostgreSQL
MySQL
SQLite
This guide assumes familiarity with:
-
开始使用 PostgreSQL、MySQL 或 SQLite
-
熟悉 Drizzle Seed
示例 1
假设你正在尝试使用下面显示的种子脚本和模式来为数据库播种。
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.
What does it mean?
目前,你有几种方法可以解决此错误:
-
你可以从
userId
列中删除非空约束; -
你可以将
users
表公开给seed
函数。模式
await seed(db, { bloodPressure, users });
- 你可以 refine
userId
列生成器;
示例 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.
What does it mean?
这意味着你既没有将 users
表提供给 seed
函数模式,也没有优化 userId
列生成器。因此,userId
列将填充 Null 值。
然后,你将有两个选择:
-
如果你同意用 Null 值填充
userId
列,则可以忽略此警告; -
否则,你可以将
userId
列生成器 refine。
改进 userId
列生成器
这样做需要 users
表在数据库中已经具有 ID,例如 1 和 2。
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();