Sequelize 多对多关系同一张表

Posted

技术标签:

【中文标题】Sequelize 多对多关系同一张表【英文标题】:Sequelize many to many relationship same table 【发布时间】:2020-09-09 22:01:16 【问题描述】:

大家好,我有一个问题。假设我们有社交媒体。

让我们想象一下 users 表是这样的。就像在任何其他社交媒体中一样,用户可以评论其他用户的照片。所以我们需要一个 cmets 表,其中包含对发布图片的用户和 cmets 图片的用户的引用。

所以我需要找到一种方法在sequelize 中创建belongsToMany

到目前为止,我有一个 accounts.ts 文件


import  AccountAttributes, Repository  from "@eneto/models";
import  DataTypes, Sequelize  from "sequelize";

/**
 * Account factory
 *
 * @param import("sequelize").Sequelize sequelize Sequelize database instance.
 * @returns Repository<AccountAttributes> Instance of Accounts Entity.
 */
function AccountFactory (sequelize: Sequelize): Repository<AccountAttributes> 
    return sequelize.define("accounts", 
        id: 
            type: DataTypes.BIGINT,
            allowNull: false,
            unique: true,
            primaryKey: true,
            autoIncrement: true,
        ,
        username: 
            type: DataTypes.STRING,
            allowNull: false,
            unique: true,
        ,
        psswrd: 
            type: DataTypes.STRING,
            allowNull: false,
        ,
        createdAt: 
            type: DataTypes.DATE,
            allowNull: false,
            defaultValue: DataTypes.NOW,
        ,
        updatedAt: 
            type: DataTypes.DATE,
            allowNull: false,
            defaultValue: DataTypes.NOW,
        ,
    ) as Repository<AccountAttributes>;


export  AccountFactory ;

在我的 index.ts 上我有这样的:

import  DB  from "@eneto/models";
import  Sequelize  from "sequelize";
import  env  from "../utils/env-vars";
import  AccountInfoFactory  from "./account-info";
import  AccountFactory  from "./accounts";

const sequelize = new Sequelize(env["ENETO_DB_NAME"], env["ENETO_DB_USER"], env["ENETO_DB_PASSWORD"], 
    port: env["ENETO_DB_PORT"],
    host: env["ENETO_DB_HOST"],
    dialect: "postgres",
    pool: 
        min: 0,
        max: 5,
        acquire: 30000,
        idle: 10000,
    ,
);

const Accounts = AccountFactory(sequelize);
const AccountTypes = AccountTypesFactory(sequelize);
const AccountAddress = AddressFactory(sequelize);
const SocialMedia = SocialMediaFactory(sequelize);
const Educations = EducationFactory(sequelize);

AccountTypes.hasMany(Accounts);
AccountAddress.hasMany(Accounts);
Accounts.hasMany(SocialMedia);
Accounts.hasMany(Educations);
Accounts.hasMany(Experiences);
Accounts.hasMany(AccountInfo);
Accounts.hasMany(Media);

// I still dont know how to make a
Accounts.belongsToMany(Accounts);

export const db: DB = 
    Accounts,
    sequelize,
;

【问题讨论】:

【参考方案1】:

找到答案:

Accounts.belongsToMany(Accounts, through: Comments,as: "to", foreignKey: "id" );
Accounts.belongsToMany(Accounts,  through: Comments, as: "from", foreignKey: "id" );

【讨论】:

以上是关于Sequelize 多对多关系同一张表的主要内容,如果未能解决你的问题,请参考以下文章

如何查询多对多关系sequelize?

如何在 Sequelize 中按多对多关系排序?

Sequelize 查询在多对多关系中显示附加数据

从多对多关系中获取结果

Sequelize 多对多自引用

Sequelize:多对多表(CROSS TABLE)关联到另一个表