【发布时间】:2021-04-13 19:27:30
【问题描述】:
我自己开一家店。在用户表中,您需要填写订单、我的产品和用户购买的产品等字段。您需要将 3 个表连接在一起(USERS、ORDERS、GOODS)。 我擅长仅将“我的产品”链接到 GOODS 表。即在创建(添加)产品时,它会自动在 GOODS 表中创建,并立即附加到 USER 表中的“我的商品”字段。现在我需要将 USER 表中的 2 个字段与 ORDERS 表中的其他 2 个字段连接起来,但要么它给我一个错误,要么只在 ORDERS 表中创建订单,而没有附加到 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;}
订单表:
@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')
}
【问题讨论】:
标签: node.js postgresql sequelize.js nestjs