Sequelize Many to Many failing with 'is not associated to' when trying to associate entries?

独自空忆成欢 提交于 2019-12-10 10:49:49

问题


I am having a problem with my many to many configuration with Sequelize, where it complains that site_article_keyword is not associated to article_keyword. The code below represents a minimal test case to try to understand what I am doing wrong (I hoped to provide something smaller, but this is what I have). I am using bluebird for the Promise API.

const Sequelize = require('sequelize');

var sequelize = new Sequelize(undefined, undefined, undefined, {
    dialect: 'sqlite',
    storage: './mydatabase',
});

const SiteArticle = sequelize.define('site_article', {
    id: {
        type: Sequelize.INTEGER,
        primaryKey: true,
        autoIncrement: true
    },
    ownerId: {
        type: Sequelize.INTEGER,
        field: 'owner_id'
    },
    title: Sequelize.STRING
        // other fields omitted
}, {
    timestamps: true
});

const ArticleKeyword = sequelize.define('article_keyword', {
    id: {
        type: Sequelize.INTEGER,
        primaryKey: true,
        autoIncrement: true
    },
    name: Sequelize.STRING,
    language: Sequelize.STRING
        // other fields omitted
}, {
    timestamps: true
});

const SiteArticleKeyword = sequelize.define('site_article_keyword', {
    siteArticleId: {
        type: Sequelize.INTEGER,
        field: 'site_article_id',
        references: {
            model: SiteArticle,
            key: 'id'
        }
    },
    articleKeywordId: {
        type: Sequelize.INTEGER,
        field: 'article_keyword_id',
        references: {
            model: ArticleKeyword,
            key: 'id'
        }
    }
    // other fields omitted
}, {
    timestamps: true
});

(ArticleKeyword).belongsToMany(
    SiteArticle, { through: SiteArticleKeyword });

(SiteArticle).belongsToMany(
    ArticleKeyword, { through: SiteArticleKeyword });

That's the model defined, now for trying to create the source and destination entries, that I then want to associate. The failure happens on the line where I call ArticleKeyword.findAll():

sequelize.sync({}).then(function() {

    // populate some data here

    let siteArticle;

    SiteArticle.create({
        ownerId: 1,
        title: 'hello world'
    }).then(function(entry) {
        siteArticle = entry;
        console.log('site article: ', JSON.stringify(entry, undefined, 2));

        return ArticleKeyword.findOrCreate({
            where: {
                name: 'keyword1',
                language: 'en'
            }
        });
    }).spread(function(entry, success) {
        console.log('article keyword: ', JSON.stringify(entry, undefined, 2));
        return siteArticle.addArticle_keyword(entry);
    }).spread(function(entry, success) {
        console.log('site article keyword: ', JSON.stringify(entry, undefined, 2));

        const siteArticleId = 1;
        const language = 'en';

        return ArticleKeyword.findAll({
            where: {
                language: language,
            },
            include: [{
                model: SiteArticleKeyword,
                where: {
                    siteArticleId: siteArticleId
                }
            }]
        });
    }).then(function(articleKeywords) {
        if (articleKeywords) {
            console.log('entries: ', JSON.stringify(articleKeywords, undefined, 2));
        } else {
            console.log('entries: ', 'none');
        }
    }).catch(function(error) {
        console.log('ERROR: ', error);
    }.bind(this));

}).catch(function(error) {
    console.log(error);
});

I am basing my code on the 'Mixin BelongsToMany' example in the Sequelize documentation.

Can anyone suggest what I am doing wrong?


回答1:


In through relationships the following should work

ArticleKeyword.findAll({
  include: [{
    model: SiteArticle,
    through: {
      attributes: ['createdAt', 'startedAt', 'finishedAt'],
      where: {siteArticleId: siteArticleId
    }
  }]
});



回答2:


The issue turns out that the reason site_article_keyword is not associated is because it is the association! With that in mind the code becomes:

return ArticleKeyword.findAll({
    where: {
        language: language,
    },
    include: [{
            model: SiteArticle,
            as: 'SiteArticle',
            siteArticleId: siteArticleId
        }]
    });

BTW one minor tweak to my code, is in the inclusion of 'as' to the belongsToMany:

ArticleKeyword.belongsToMany(
    SiteArticle,
    { through: SiteArticleKeyword, as: 'SiteArticle' }
);

SiteArticle.belongsToMany(
    ArticleKeyword,
    { through: SiteArticleKeyword, as: 'ArticleKeyword' }
);

This allows for addArticleKeyword() instead of addArticle_Keyword().



来源:https://stackoverflow.com/questions/42077987/sequelize-many-to-many-failing-with-is-not-associated-to-when-trying-to-associ

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!