在sequelize中包含belongsTo关联

时间:2018-02-03 12:25:21

标签: javascript database associations sequelize.js belongs-to

我正在关注文档中的续集示例,但我仍然坚持如何在子模型中包含父关联。

docs on associations中,模型和模型之间的关系定义如下:

arguments.length

该关联分配给Product.User,并包含在include数组中。

在sequelize minimum express application中,模型在单独的文件中定义,并且通过调用模型上的方法来建立关联。在这种情况下,我有Message和User,在一条消息和它的用户之间有belongsTo关系。

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,
  }]
});

我想我需要以某种方式从模型中获得关联。我按照文档来建立模型之间的关联:

//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;
};

但我如何Object.keys(db).forEach(modelName => { if (db[modelName].associate) { db[modelName].associate(db); } });这样,当我创建包含数组时Message.User = Message.belongsTo(User)

1 个答案:

答案 0 :(得分:0)

是的......我意识到,因为协会已经完成所有我必须做的就是包括模型:



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'}],
    });
  }
};