我已经建立了一个带有 typeorm (https://github.com/typeorm/typeorm) 和 NestJs (https://github.com/nestjs/nest) 的系统,但是 TypeORM 没有创建表或列。我的设置是这样的:
import {UserPassword} from '../user/user-password.entity';
import {User} from '../user/user.entity';
createConnection({
type: 'mysql',
host: 'typeorm2.cn32tstd6wqk.eu-central-1.rds.amazonaws.com',
port: 1234,
username: 'username',
password: 'password',
database: 'dbname',
entities: [
// __dirname + '/../**/*.entity{.ts,.js}'
UserPassword,
User
]
})
实体是:
import {Entity, Column, PrimaryGeneratedColumn, OneToOne, JoinColumn} from 'typeorm';
@Entity()
export class UserPassword {
@PrimaryGeneratedColumn()
id: number;
@Column()
hash: string;
@Column()
algorithm: string;
}
和
import {Entity, Column, PrimaryGeneratedColumn, OneToOne, JoinColumn} from 'typeorm';
import {UserPassword} from './user-password.entity';
@Entity()
export class User {
@PrimaryGeneratedColumn()
id: number;
@Column({ length: 35 })
firstName: string;
@Column({ length: 35 })
lastName: string;
@Column({ length: 50})
mail: string;
@OneToOne(type => UserPassword)
@JoinColumn()
password: UserPassword;
}
然后我尝试创建一个这样的用户:
// ... some code
await this.userPasswordRepository.save(userPassword);
return await this.userRepository.save(user);
但是我收到以下错误:
QueryFailedError:ER_NO_SUCH_TABLE:表“typeorm2.user_password”不存在
当我手动插入表格时,出现错误:
QueryFailedError:ER_BAD_FIELD_ERROR:“字段列表”中未知的列“哈希”
所以看来 TypeORM 不会生成表/列。有谁知道为什么会这样?
尽管前面的答案对于开发环境是可以接受的,但对于生产来说是错误的。
您正在寻找的是迁移。建立连接并记录时执行迁移 - 迁移不会运行多次。 TypeORM 还提供 CLI,允许您生成迁移(createConnection({
type: 'mysql',
host: 'typeorm2.cn32tstd6wqk.eu-central-1.rds.amazonaws.com',
port: 1234,
username: 'username',
password: 'password',
database: 'dbname',
entities: [
// __dirname + '/../**/*.entity{.ts,.js}'
UserPassword,
User
],
migrations: ['./migrations/*.js'],
synchronize: false
})
迁移由两部分组成 - up(迁移代码)和down(恢复迁移的代码)。简单的例子:
import { MigrationInterface, QueryRunner } from 'typeorm';
export class AddImageToUser implements MigrationInterface {
async up(queryRunner: QueryRunner): Promise<any> {
await queryRunner.query(
'ALTER TABLE "user" ADD image varchar(255)'
);
}
async down(queryRunner: QueryRunner): Promise<any> {
await queryRunner.query(
'ALTER TABLE "user" DROP COLUMN image'
);
}
}
如果您想了解更多信息,TypeORM 在其官方 Git 存储库上有详细说明一般来说,将数据和模式的同步交给框架是不好的。您应该执行此操作以确保保留数据库架构。我之前链接的 CLI 还允许您运行迁移,因此在将更改推送到生产之前对其进行测试。
const connection = await createConnection(...);
await connection.synchronize();
export let dbOptions: ConnectionOptions = {
type: "mysql",
host: "localhost",
port: 3306,
username: "root",
password: "root",
database: "exam",
synchronize: true,
entities: [
// "./entities/*.js", // Wildcard Path : Not working
EmployeeEntity // Specify the entities directly.
]
}
ormconfig.json/js/xml/etc
:
synchronize: true
如果表不存在,它会创建一次。
这应该有效
{
"type": "mysql",
"host": "localhost",
"port": 5432,
"username": "root",
"password": "root",
"database": "Identity_Demo",
"synchronize": true,
"logging": true,
"entities": ["dist/**/*.entity.js"]
}
@Entity({ name: 'User' })
0.1.0-alpha.40,在创建连接时有选项 autoSchemaSync
,这使其工作:
createConnection({
type: 'mysql',
host: 'typeorm2.cn32tstd6wqk.eu-central-1.rds.amazonaws.com',
port: 1234,
username: 'username',
password: 'password',
database: 'dbname',
entities: [
// __dirname + '/../**/*.entity{.ts,.js}'
UserPassword,
User
],
autoSchemaSync: true,
})
synchronize: true
可能会解决问题,但对于面临类似问题的人来说,尽管存在
synchronize: true
,但可能还有其他原因。其中一些是:
@Entity()
装饰你的实体,以便
typeORM
可以识别它并生成表格(仅当
synchronize
是
true
时)。
@Module({
imports: [TypeOrmModule.forFeature([<Your_Entity>])],
.......
})
完成这些后,将自动创建表格。但是,使用synchronize: true
安全吗?可能是@Jiri Kralovec 回答的另一个话题。
如果您第一次使用
typeorm-model-generator
生成从数据库到代码的实体,那么
typeorm-model-generator
可能会使用类似的内容生成您的代码。
@Entity('yourTableName', { schema: 'public' })
我删除了{ schema: 'public' }
留下它就像
@Entity('yourTableName')
这解决了我的问题。
希望它对将来的人有所帮助:)
...
synchronize: true,
...
TypeOrm 配置
data-source.ts:
typeorm-ts-node-commonjs schema:sync --dataSource data-source.ts
如果数据源文件是JavaScript,则可以使用以下命令:
typeorm schema:sync --dataSource data-source.js
synchronize: true
。
所有配置都是正确的,只是我的实体文件在所有更改后没有保存。
一定要打开自动保存。