typescript 如何在TypeORM中初始化实体后将其添加到数据源

zqdjd7g9  于 2023-06-30  发布在  TypeScript
关注(0)|答案(1)|浏览(183)

初始实体定义如下

import { Entity, PrimaryGeneratedColumn} from "typeorm"

@Entity()
export class Product {
    @PrimaryGeneratedColumn()
    id: number

使用以下代码初始化DataSource

import { DataSource } from "typeorm"
import { Cart } from "../entity/Product"

export const AppDataSource = new DataSource({
    type: "postgres",
    host: "localhost",
    port: 5432,
    username: "engineerhead",
    password: "",
    database: "test",
    synchronize: true,
    logging: false,
    entities: [ Product ],
    migrations: [],
    subscribers: [],
})

export default async () => {
    await AppDataSource.initialize();
}

在设置代码中,数据库被初始化

import initDB from "./data-source.ts"

await initDB();

现在我有另一个实体,它必须在运行时添加

import { Entity, PrimaryGeneratedColumn} from "typeorm"

@Entity()
export class Cart{
    @PrimaryGeneratedColumn()
    id: number

我试图从选项对象中获取实体数组,但它是只读的

import AppDataSource from "./data-source"

const ents = AppDataSource.options.entities;

如何在运行时将cart初始化后添加到DataSource的实体数组中?

4smxwvx5

4smxwvx51#

你不能向实体添加数据的原因是因为你只定义了id,你必须设置实体的属性,就像下面这样:

@Entity()
export class Product {

@PrimaryGeneratedColumn()
id: number

 @Column()
 username: string;

 @Column()
 password: string;

 @Column()
 email: string;

尝试查看typeorm文档以获取一些参考:https://typeorm.io/

相关问题