Z
Z
Zomdies2021-06-10 20:19:49
PostgreSQL
Zomdies, 2021-06-10 20:19:49

How to create a many-to-many relationship through one table?

It is necessary to describe the model using the CodeFirst approach. There is a user, and he must have the role of friends, which will refer us to the user. I created 2 models, but I can't figure out how to connect them. How can I set up an association?
User
60c2494759df7826347284.png
Model Friend Model
60c249695f8f8255927260.png

@Table({tableName: 'friends', createdAt: false, updatedAt: false})
export class Friend extends Model<Friend,FriendCreationAttrs> {

    
    @Column({type: DataType.INTEGER, unique: true, primaryKey: true, autoIncrement: true})
    id: number;

    @ForeignKey(() => User)
    @Column({type: DataType.INTEGER})
    UserIdFrom: number;

    @ForeignKey(() => User)
    @Column({type: DataType.INTEGER})
    UserIdTo: number;
}


@Table({tableName: 'users',createdAt: false, updatedAt: false})
export class User extends Model<User, UserCreationAttrs> {


    @Column({type: DataType.INTEGER, unique: true, primaryKey: true, autoIncrement: true})
    id: number;

    @Column({type: DataType.STRING, unique: true, allowNull: false})
    email: string;

    @Column({type: DataType.STRING, allowNull: false})
    password: string;
}

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question