Answer the question
In order to leave comments, you need to log in
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
Model Friend Model
@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 questionAsk a Question
731 491 924 answers to any question