D
D
Dmitry .2020-12-30 10:02:27
PostgreSQL
Dmitry ., 2020-12-30 10:02:27

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;
}

user model.
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

1 answer(s)
Y
Yuriy Vorobyov, 2020-12-30
@MrProper5050

In products, do this:

@BelongsTo(() => User)
  user: User;

  @ForeignKey(() => User)
  @Column({
    type: DataType.STRING,
    allowNull: false,
  })
  userId: string;

In users like this:
@HasMany(() => Goods)
  userGoods: Goods[];

Then write a function for adding products and write them together in the user id in the corresponding field, and when you make a selection, use include if you need to get products by user or user by product

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question