Answer the question
In order to leave comments, you need to log in
How to work with associations in sequelize in Nest.JS?
I am making my own pseudo engine for the store. Each store has products and users who can display those products or buy. How can I make a connection between the user who posted the product and the product?
I understand that there are all sorts of @HasOne, @ForeignKey and so on, but I don’t understand how to use them at all and how to change the array of products for the user later.
Product model.
import { AllowNull, BelongsTo, Column, CreatedAt, DataType, ForeignKey, Model, PrimaryKey, Table, UpdatedAt } from "sequelize-typescript";
import { User } from "./user.model";
@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;
@ForeignKey(() => User)
@Column
userId: any;
@BelongsTo(() => User)
user: User;
@CreatedAt
@Column
createdAt: Date;
@UpdatedAt
@Column
updatedAt: Date;
}
import { Column, CreatedAt, DataType, HasMany, Model, PrimaryKey, Table, UpdatedAt } from "sequelize-typescript";
import { Goods } from "./goods.model";
@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;
@Column(DataType.ARRAY(DataType.JSON))
purchasedGoods: any
@HasMany(()=> Goods)
myGoods: Goods[]
@CreatedAt
@Column
createdAt: Date;
@UpdatedAt
@Column
updatedAt: Date;
}
Answer the question
In order to leave comments, you need to log in
In products, do this:
@BelongsTo(() => User)
user: User;
@ForeignKey(() => User)
@Column({
type: DataType.STRING,
allowNull: false,
})
userId: string;
@HasMany(() => Goods)
userGoods: Goods[];
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question