taobataoma
taobataoma

Reputation: 19

How to set the associations in Sequelize

I has two model, define is here:

User model:

var Sequelize = require("sequelize");
module.exports = function (sequelize) {
    var User = sequelize.define('user', {
        name:{ type:Sequelize.STRING(50), defaultValue:''},
        email:Sequelize.STRING(50),
        password:Sequelize.STRING(256)
    },
    {
        associate: function (models) {
            User.hasMany(
                models.Article,
                { foreignKey: 'postUserId' }
            );
            User.hasMany(
                models.Article,
                { foreignKey: 'editUserId' }
            );
            User.hasMany(
                models.Article,
                { foreignKey: 'deleteUserId' }
            );
        }
    });

    return User;
};

Article modle:

module.exports = function (sequelize, DataTypes) {
    var Article = sequelize.define('Article', {
        title: {type: DataTypes.STRING, defaultValue: '' },
        content: { type: DataTypes.STRING, defaultValue: '' }
    },
    {
        associate: function (models) {
            Article.belongsTo(
                models.User,
                { foreignKey: 'postUserId' }
            );
            Article.belongsTo(
                models.User,
                { foreignKey: 'editUserId' }
            );
            Article.belongsTo(
                models.User,
                { foreignKey: 'deleteUserId' }
            );
        }
    });

    return Article;
};

in my table, every record has three userid references to model User. I want to get all the three User data in per record. how can i to define the associate and how to write the find function.

db.Article.findById('9100', {include: [User]}).then(function (art) {
    if (!art) {
        return res.status(404).send({
            message: 'No article with that identifier has been found'
        });
    }
    res.json(art);
}).catch(function (err) {
    return res.status(400).send({
        message: errorHandler.getErrorMessage(err)
    });
});

the method of above only can return one User Data, how to return the all User Data?

thx.

Upvotes: 1

Views: 3662

Answers (1)

Adam
Adam

Reputation: 5233

If you associate the same models multiple times, you have to use the 'as' property in your association.

associate: function (models) {
            User.hasMany(
                as:'PostArticles',
                models.Article,
                { foreignKey: 'postUserId' }
            );
            User.hasMany(
                models.Article,
                as:'EditArticles',
                { foreignKey: 'editUserId' }
            );
            User.hasMany(
                models.Article,
                as:'DeleteArticles',
                { foreignKey: 'deleteUserId' }
            );
        }

More: http://docs.sequelizejs.com/en/latest/docs/associations/

Upvotes: 1

Related Questions