Volde
Volde

Reputation: 23

Sequelizejs is not associated to

I made some associate but it did not work, probably with me that something is wrong, ask for help. There are two models

module.exports = function (sequelize, DataTypes) {
var pages_lang = require('./pages_lang')(sequelize, DataTypes);
return sequelize.define('pages', {
    id: {
        type: DataTypes.INTEGER(10),
        allowNull: false,
        primaryKey: true,
        autoIncrement: true,
        references :  { model: "pages_lang", key: "page_id" }
    },
    name: {
        type: DataTypes.STRING,
        allowNull: false
    },
    published: {
        type: DataTypes.BOOLEAN,
        allowNull: false,
        defaultValue: '0'
    },
    createdAt: {
        type: DataTypes.DATE,
        allowNull: false,
        defaultValue: '0000-00-00 00:00:00'
    },
    updatedAt: {
        type: DataTypes.DATE,
        allowNull: false,
        defaultValue: '0000-00-00 00:00:00'
    }
}, {
    classMethods: {
        associate: function (models) {
            this.hasMany(models.pages_lang, {onDelete: 'SET NULL', onUpdate: 'CASCADE', foreignKey: 'page_id', as: 'pages', through: models.pages_lang});
        },
        getAll() {
            return this.findAll({include: [{model: pages_lang, as: 'pages_lang'}]}).then(function (result) {
                return result;
            });
        }
    }
});

};

module.exports = function (sequelize, DataTypes) {
return sequelize.define('pages_lang', {
    id: {
        type: DataTypes.INTEGER(10),
        allowNull: false,
        primaryKey: true,
        autoIncrement: true
    },
    page_id: {
        type: DataTypes.INTEGER(10),
        allowNull: false,
        references :  { model: "pages", key: "id" }
    },
    content: {
        type: DataTypes.TEXT,
        allowNull: false
    }
}, {
    classMethods: {
        associate: function (models) {
            this.belongsTo(models.pages, {foreignKey: 'id', foreignKeyConstraint:true, as: 'pages', through: models.pages});
        }
    }
});

};

But when you call results in an error

Unhandled rejection Error: pages_lang (pages_lang) is not associated to pages!

Advance very grateful for the help

Upvotes: 2

Views: 6671

Answers (1)

Jan Aagaard Meier
Jan Aagaard Meier

Reputation: 28778

Your association alias (as) should match what you pass to findAll

this.hasMany(models.pages_lang, {onDelete: 'SET NULL', onUpdate: 'CASCADE', foreignKey: 'page_id', as: 'pages_lang' });

return this.findAll({include: [{model: pages_lang, as: 'pages_lang'}]});

Since the model is already called pages_lang, you can also skip the alias completely:

this.hasMany(models.pages_lang, {onDelete: 'SET NULL', onUpdate: 'CASCADE', foreignKey: 'page_id'});

return this.findAll({include: [pages_lang]});

Notice that I removed the through argument - it should only be used for belongsToMany (many-to-many)

Upvotes: 2

Related Questions