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

标签 javascript node.js postgresql orm sequelize.js

我有用户,我想实现添加 friend 。
因此,这会创建多对多关系,如何在使用相同实例时使用 sequelize 创建多对多关系?

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

但我不知道如何处理外键以及它们将被称为什么

最佳答案

下面使用 "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();
  }
})();

它将创建存储对象 ID 的表 user_friends。查看数据库中的数据记录:

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)

您可以调用 userInstance.getFriends() 来获取一些用户的 friend 。

关于javascript - 使用同一实例建立多对多关系,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60921775/

相关文章:

javascript - 如何使用 select 标签的 title 属性删除选中的选项

javascript - 具有 ID 的 DOM 树元素是否成为全局属性?

node.js - 使用 M1 在 dockerized Linux 上安装 Node Canvas

node.js - 如何使用 babel 构建非 js 文件?

PHP:shell_exec 一个 shell 脚本与 shell_exec 一个 linux 上的程序(权限)

database - 具有 git 语义的数据库表的最佳模式?

javascript - 滚动时锁定表格标题 (ColResizable)

javascript - 使用node js关闭.exe文件

postgresql - PostgreSQL 中奇怪的幽灵记录——它们是什么?

java - preparedStatement.getBigDecimal 其中值为 null