简体   繁体   English

使用同一实例建立多对多关系

[英]Sequelize many to many relationship with same instance

I have users and i wantk to implements adding friends.我有用户,我想实现添加朋友。 So this creates a many to many relationship, how can i create a many to many relationship with sequelize when using the same instance?所以这会创建一个多对多的关系,我如何在使用同一个实例时使用 sequelize 创建多对多的关系?

User.belongsToMany(User, {as: "friends", through: "friends})

but i can't figure out how to do with the foreign keys and what they are going to be called但我不知道如何处理外键以及它们将被称为什么

Below example using "sequelize": "^5.21.3" :下面使用"sequelize": "^5.21.3"示例"sequelize": "^5.21.3"

import { sequelize } from '../../db';
import { Model, DataTypes, BelongsToManyAddAssociationMixin } from 'sequelize';

class User extends Model {
  public getFriends!: BelongsToManyAddAssociationMixin<User, string>;
}
User.init(
  {
    name: DataTypes.STRING,
  },
  { sequelize, modelName: 'users' },
);

User.belongsToMany(User, { as: 'friends', through: 'user_friends' });

(async function test() {
  try {
    await sequelize.sync({ force: true });
    // seed
    const friendsOfUser1 = [{ name: 'james' }, { name: 'elsa' }];
    const friendsOfUser2 = [{ name: 'jane' }, { name: 'mike' }];
    await User.bulkCreate(
      [
        { name: 'jeremy', friends: friendsOfUser1 },
        { name: 'lynne', friends: friendsOfUser2 },
      ],
      { include: [{ model: User, as: 'friends' }] },
    );
    const jeremy = await User.findOne({ where: { name: 'jeremy' } });
    const firendsOfJeremy = await jeremy.getFriends();
    console.log(firendsOfJeremy);
  } catch (error) {
    console.log(error);
  } finally {
    await sequelize.close();
  }
})();

It will create the table user_friends which stores the ids of the objects.它将创建存储对象 ID 的表user_friends Check the data records in the database:查看数据库中的数据记录:

node-sequelize-examples=# select * from user_friends;
 userId | friendId
--------+----------
      1 |        3
      1 |        4
      2 |        5
      2 |        6
(4 rows)

node-sequelize-examples=# select * from users;
 id |  name
----+--------
  1 | jeremy
  2 | lynne
  3 | james
  4 | elsa
  5 | jane
  6 | mike
(6 rows)

You can call userInstance.getFriends() to get some user's friends.您可以调用userInstance.getFriends()来获取一些用户的好友。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM