- 【TS全栈开发-chapter11】
src/database/seed/category.ts 中categroy data如果一个parent创建多个child,会导致path重复seed失败
修改data如下:
const data: Item[] = [
{
name: '技术文集',
children: [
{ name: '个人开发', children: [{ name: 'MCP工具' }, { name: '网页开发' }] },
{ name: '课程', children: [{ name: 'TS全栈开发' }] },
],
},
{ name: '创业笔记', children: [{ name: '码农创业记' }] },
{ name: '生活随笔' },
{ name: '探索世界' },
];
执行"dbmrs": "cross-env NODE_ENV=development prisma migrate reset -f",,报错
PrismaClientKnownRequestError:
Invalid `prisma.category.create()` invocation:
Unique constraint failed on the fields: (`path`)
at ri.handleRequestError (/opt/code/wmc/amingos/node_modules/.pnpm/@prisma+client@6.12.0_prisma@6.12.0_typescript@5.9.2__typescript@5.9.2/node_modules/@prisma/client/src/runtime/RequestHandler.ts:228:13)
at ri.handleAndLogRequestError (/opt/code/wmc/amingos/node_modules/.pnpm/@prisma+client@6.12.0_prisma@6.12.0_typescript@5.9.2__typescript@5.9.2/node_modules/@prisma/client/src/runtime/RequestHandler.ts:174:12)
at ri.request (/opt/code/wmc/amingos/node_modules/.pnpm/@prisma+client@6.12.0_prisma@6.12.0_typescript@5.9.2__typescript@5.9.2/node_modules/@prisma/client/src/runtime/RequestHandler.ts:143:12)
at async l (/opt/code/wmc/amingos/node_modules/.pnpm/@prisma+client@6.12.0_prisma@6.12.0_typescript@5.9.2__typescript@5.9.2/node_modules/@prisma/client/src/runtime/getPrismaClient.ts:862:24) {
code: 'P2002',
meta: { modelName: 'Category', target: [ 'path' ] },
clientVersion: '6.12.0'
}
An error occurred while running the seed command:
Error: Command failed with exit code 1: ts-node --compiler-options {"module":"CommonJS"} -r tsconfig-paths/register src/database/seed/index.ts
ELIFECYCLE Command failed with exit code 1.
问题定位:因为把整个 parent 对象传给 createChild,导致在内存中使用的是旧的 parent 快照(还没包含第一个子节点的信息),所以第二个子节点计算出的 path 跟第一个一样。
我自己临时修改方案(修改parent中numchild):
const createCategory = async (item: Item, parent?: Category) => {
let category: Category;
const { name, children } = item;
const slug = generateLowerString(name);
if (isNil(parent)) {
category = await prisma.category.createRoot({
data: { name, slug },
});
} else {
category = await prisma.category.createChild({
node: parent,
data: { name, slug },
});
+ parent.numchild += 1;
}
if (!isNil(children)) {
for (const child of children) {
await createCategory(child, category);
}
}
};
请课程修复一下,多谢