根据typeorm-seeding指南,我创建了下面的一些文件:
- database/factories/post.factory.ts
- database/seeds/post.seed.ts
post.factory.ts
import { define } from 'typeorm-seeding';
import { Post } from '../../src/entity';
define(Post, (faker: typeof Faker) => {
return new Post({
id: faker.random.uuid(),
title: 'test',
body: 'test',
});
});
字符串
post.seed.ts
import { Factory, Seeder } from 'typeorm-seeding';
import { Connection } from 'typeorm';
import { Post } from '../../src/entity';
export default class PostSeeder implements Seeder {
public async run(factory: Factory, _connection: Connection): Promise<any> {
await factory(Post)().createMany(10);
}
}
型
当运行npm run seed:run
时,它导致了一个错误:
❌ Could not save entity
QueryFailedError: null value in column "title" of relation "posts" violates not-null constraint
query: 'INSERT INTO "blog"."posts"("id", "title", "body", "created_at", "updated_at") VALUES (DEFAULT, DEFAULT, DEFAULT, DEFAULT, DEFAULT) RETURNING "id", "title", "created_at", "updated_at"',
parameters: [],
detail: 'Failing row contains (111111111-2a7d-4316-9a85-4d38d6e3febb, null, null, 2022-11-26 03:28:54.895454, null).',
型
package.json中的seed脚本:
{
"name": "blog",
"version": "0.0.1",
"description": "Blog",
"main": "index.js",
"scripts": {
"seed:run": "ts-node -r tsconfig-paths/register ./node_modules/typeorm-seeding/dist/cli.js seed -c seed",
...
"dependencies": {
"typeorm-seeding": "^1.6.1",
...
型
种子相关的ormconfig.js:
module.exports = [
{
name: 'seed',
type: 'postgres',
host: process.env.DB_HOST,
port: process.env.DB_PORT,
username: process.env.USERNAME,
password: process.env.DB_PASSWORD,
database: process.env.DB_NAME,
schema: 'blog',
uuidExtension: 'pgcrypto',
synchronize: false,
logging: false,
entities: ['src/entity/index.ts'],
factories: ['database/factories/**/*.factory.ts'],
seeds: ['database/seeds/**/*.seed.ts'],
cli: {
entitiesDir: 'src/entity',
migrationsDir: 'database/migrations',
},
},
型
运行seed时似乎无法从工厂获取参数。哪里错了?
1条答案
按热度按时间mtb9vblg1#
可以使用Typeorm-faker
就像这样打字
字符串