简体   繁体   中英

Including a belongsTo association in sequelize

I am following the sequelize example in the docs and I am stuck as to how to include an association to the parent in the child model.

In the docs on associations , models and the relationships between models are defined like so:

 Product.User = Product.belongsTo(User); User.Addresses = User.hasMany(Address); return Product.create({ title: 'Chair', user: { first_name: 'Mick', last_name: 'Broadstone', } }, { include: [{ association: Product.User, }] }); 

The association is assigned to Product.User, and included in the include array.

In the sequelize minimum express application the models are defined in separate files and the associations are made by calling the methods on the models. In this case I have Message and User, with a belongsTo relationship between one message and its user.

 //message.js module.exports = (sequelize, DataTypes) => { var Message = sequelize.define('Message', { content: DataTypes.STRING, authorId: DataTypes.INTEGER, }); Message.associate = function (models) { models.Message.belongsTo(models.User, { foreignKey: 'authorId', as: 'author', }); }; return Message; }; //user.js module.exports = (sequelize, DataTypes) => { var User = sequelize.define('User', { firstName: DataTypes.STRING, }); User.associate = function (models) { models.User.hasMany(models.Message, {foriegnKey: 'authorId'}); }; return User; }; 

I think I need to somehow get the association from the models. I followed the docs to make the associations between the models:

 Object.keys(db).forEach(modelName => { if (db[modelName].associate) { db[modelName].associate(db); } }); 

But how do I do Message.User = Message.belongsTo(User) such that when I create the include array do include[{association: Message.User}] ?

Right... I realised since the association was already made all I had to do was include the model:

 const createMessage = async (message) => { const author = await findUser(message.author); if (author) { const authorId = author.dataValues.id; return db.Message.create({ content: message.content, authorId: authorId, }); } else { return db.Message.create({ author: { firstName: message.author, }, content: message.content, }, {include:[{model: db.User, as: 'author'}], }); } }; 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM