如何在 Sequelize 中创建这种关系

How to create this relationship in Sequelize

我对下面的关系有问题(看下图)。我不知道,如何在 Sequelize 中创建 ArticleAbout :( 我已经创建了产品、品牌和文章模型。我现在应该做什么?

取决于文章与品牌和产品的相关程度(我假设任何一篇文章都可以引用多个产品 and/or 多个品牌)。 实现这一目标的最佳方法是建立从文章到产品和品牌的 n:m 关系。文档在这里更详细地解释了这一点: Sequelize Docs - Association#Scopes

所以,例如:

Article = sequelize.define('article', {
    title: DataTypes.String,
    text: DataTypes.TEXT
});

ArticleAbout = sequelize.define('article_about', {
    about_id: {
        type: DataTypes.INTEGER,
        unique: 'about_article_ref'
    },
    about: {
        type: DataTypes.STRING,
        unique: 'about_article_ref',
    },
    reference_id: {
        type: DataTypes.INTEGER,
        unique: 'about_article_ref',
        references: null
    }
});

Brand.belongsToMany(Article, {
    through: {
        model: ArticleAbout,
        unique: false.
        scope: {
            about: 'brand'
        }
    },
    foreignKey: 'reference_id',
    constraints: false
});

Product.belongsToMany(Article, {
    through: {
        model: ArticleAbout,
        unique: false.
        scope: {
            about: 'product'
        }
    },
    foreignKey: 'reference_id',
    constraints: false
});

Article.belongsToMany(Brand, {
    through: {
        model: ArticleAbout,
        unique: false
    },
    foreignKey: 'about_id'
});

Article.belongsToMany(Product, {
    through: {
        model: ArticleAbout,
        unique: false
    },
    foreignKey: 'about_id'
});

关键部分是 unique: 'string'through:

通过设置字符串的唯一性,您是在告诉 Sequelize 将该键组合为复合键的一部分,这意味着多个对象可以与一个键相关联。 constraints: false 指示编译器停止对所有 cross-reference 外键尖叫。

设置 through: 通过 table 建立关系,就像您在您正在使用的 AboutArticle table 中描述的那样。

然后您就可以开始为产品和品牌添加文章了:

product.addArticle(article);
brand.addArticle(article);

其中,查询 table 变得非常简单:

Article.getProducts();
Article.getBrands();
Product.getArticles();
Brand.getArticles();

希望对您有所帮助。