你好,我正在开始一个使用 TypeScript、TypeORM 和 Postgres 的项目。我创建了似乎正确的实体,但出现了一些我不理解的错误。发现的问题是关系@ManyToOne - @One ToMany 之间。这是我的声明和控制台错误。
// Entity for products table
import { Category } from './categories/categories.entity';
import { OrderDetails } from 'src/orders/details/orderDetails.entity';
import {
Column,
Entity,
JoinTable,
ManyToMany,
ManyToOne,
PrimaryGeneratedColumn,
} from 'typeorm';
@Entity({name: 'products`})
export class Product {
@PrimaryGeneratedColumn('uuid')
id: string;
@Column({ length: 50, nullable: false })
name: string;
@Column({ nullable: false })
description: string;
@Column('decimal', { precision: 10, scale: 2, nullable: false })
price: number;
@Column({ nullable: false })
stock: number;
@Column({ nullable: true, default: 'default_image_url' })
imgUrl: string;
@ManyToOne(() => Category, (category) => category.products)
@JoinTable()
category: Category;
@ManyToMany(() => OrderDetails)
@JoinTable()
orderDetails: OrderDetails[];
}
// Pourpose: Entity for categories table
import { Product } from '../products.entity';
import { Column, Entity, OneToMany, PrimaryGeneratedColumn } from 'typeorm';
@Entity({ name: 'categories' })
export class Category {
@PrimaryGeneratedColumn('uuid')
id: string;
@Column({ length: 50, nullable: false })
name: string;
@OneToMany(() => Product, (product) => product.category)
products: Product[];`
}
这是错误: src/categories/categories.entity.ts:22:4 - 错误 TS2554:预期有 2-3 个参数,但得到了 1 个。 22 @OneToMany(() => 产品) ~~~~~~~~~ node_modules/typeorm/decorator/relations/OneToMany.d.ts:8:102 8 导出声明函数 OneToMany(typeFunctionOrTarget: string | ((type?: any) => ObjectType), inverseSide: string | ((object: T) => any), options?: RelationOptions): PropertyDecorator; ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 未提供“inverseSide”的参数。 src/categories/categories.entity.ts:22:20 - 错误 TS2552:找不到名称“产品”。您指的是“产品”吗? 22 @OneToMany(() => 产品) ~~~~~~~~~ src/categories/categories.entity.ts:24:13 - 错误 TS2552:找不到名称“产品”。您指的是“产品”吗? 24 个产品:产品[]; ~~~~~~~~~ src/categories/categories.entity.ts:24:13 - 错误 TS4031:导出类的公共属性“产品”具有或正在使用私有名称“产品”。 24 个产品:产品[]; ~~~~~~~~~ [10:37:23] 发现 4 个错误。观察文件更改。
所有声明都是正确的,但我不明白发生了什么。对我来说,这似乎是 TypeScript、Pretier 上的一个错误。我尝试使用空对象 {} 和 {cascade: true} 添加第二个参数,但它不起作用
你可以这样做:
@Column({ nullable: false })
category_id: number;
@ManyToOne(() => Category, (category) => category.id, {
nullable: false,
onDelete: "CASCADE",
onUpdate: "CASCADE",
})
@JoinColumn({
name: "category_id",
foreignKeyConstraintName: "category_fk",
})
category: Category;
@ManyToMany(() => OrderDetails)
@JoinTable({
name: "order_rel",
joinColumn: { name: "rel_id" },
inverseJoinColumn: { name: "order_id" },
})
orderDetails: OrderDetails[];