簡體   English   中英

Sequelize 多對多關系同一張表

[英]Sequelize many to many relationship same table

大家好,我有一個問題。 假設我們有社交媒體。

在此處輸入圖像描述

讓我們想象一下 users 表看起來像這樣。 就像在任何其他社交媒體中一樣,用戶可以評論其他用戶的照片。 所以我們需要一個評論表,其中包含對發布圖片的用戶和評論圖片的用戶的引用。 在此處輸入圖像描述

所以我需要找到一種在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,
};

找到了答案:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM