Sequelize不加入关系



我自己做一家商店。在用户表中,您需要制作字段订单、我的产品和用户购买的产品。您需要将3个表(USERS、ORDERS、GOOD(连接在一起。我只擅长链接";我的产品";到货物表。也就是说,当一个产品被创建(添加(时,它被自动创建在货物表中,并立即附加到";我的商品;USER表中的字段。现在,我需要将USER表中的2个字段与ORDERS表中的其他2个字段连接起来,但这要么会给我一个错误,要么订单只在ORDERS表上创建,而没有附加到USERS表中的字段。帮帮我。USERS表格:

@Table({tableName:'users'})export class User extends Model<User>{
@PrimaryKey
@Column
id: string;
@Column
username: string;
@Column
email: string;
@Column(DataType.STRING(255))
password: string;
@Column
role: string;
@Column
balance: number;
@HasMany(() => Goods)
myGoods: Goods[]

@HasMany(() => Orders, 'SellerOrders')
orders: Orders[]
@HasMany(()=> Orders, 'BuyerPurchasedGoods')
purchasedGoods: Orders[]

@CreatedAt
@Column
createdAt: Date;
@UpdatedAt
@Column
updatedAt: Date;}

ORDERS表格:

@Table({tableName:'orders'}) export class Orders extends Model<Orders>{
@PrimaryKey
@Column
id: string;
@AllowNull(false)
@Column(DataType.JSON)
info: any;
@AllowNull(false)
@Column(DataType.STRING)
state: string;
//USER
@ForeignKey(() => User)
@Column({
type: DataType.STRING,
allowNull: false,
})
ownerId: any;
@BelongsTo(() => User, 'SellerOrders')
owner: User;
@ForeignKey(() => User)
@Column({
type: DataType.STRING,
allowNull: false,
})
buyerId: any;
@BelongsTo(() => User, "BuyerPurchasedGoods")
buyer: User;
//DATE
@CreatedAt
@Column
createdAt: Date;
@UpdatedAt
@Column
updatedAt: Date;}

货物表:

@Table({tableName:'goods'}) export class Goods extends Model<Goods>{

@PrimaryKey
@Column
id: string;
@AllowNull(false)
@Column
title: string;
@AllowNull(false)
@Column
category: string;
@AllowNull(false)
@Column(DataType.JSON)
info: any
@AllowNull(false)
@Column
price: number;
@AllowNull(false)
@Column
amount: number;
@BelongsTo(() => User)
user: User;
@ForeignKey(() => User)
@Column({
type: DataType.STRING,
allowNull: false,
})
userId: string;
@CreatedAt
@Column
createdAt: Date;
@UpdatedAt
@Column
updatedAt: Date;}

这就是我创建新产品的方式:

try {
const id = shortid.generate()
await this.goodsModel.create({ ...createItemDto, id, userId: user.id})
return 'OK'
} catch (error) {
throw new InternalServerErrorException('Failure to create new item')
}

订单如下:

//generate order
try {
const id = shortid.generate();
await this.ordersModel.create({
id, 
ownerId: item.userId, 
buyerId: userObj.id,
info:{ ...generateOrderDto },
state:'processing'
},
{include:[{all:true}]}
)
return 'OK'
} catch (error) {
console.log(error)
throw new InternalServerErrorException('Cannot generate order')
}

好吧,我想明白了。突然间,它帮助了某人:我在表中错误地指定了关联。您需要指定变量的名称。订单中:

@ForeignKey(() => User)
@Column({
type: DataType.STRING,
allowNull: false,
})
ownerId: any;
@BelongsTo(() => User, 'ownerId')
owner: User;
@ForeignKey(() => User)
@Column({
type: DataType.STRING,
allowNull: false,
})
buyerId: any;
@BelongsTo(() => User, 'buyerId')
buyer: User;

在用户中:

@HasMany(() => Goods)
myGoods: Goods[]

@HasMany(() => Orders, 'ownerId')
orders: Orders[]
@HasMany(()=> Orders, 'buyerId')
purchasedGoods: Orders[]

祝你好运!

最新更新