为了账号安全,请及时绑定邮箱和手机立即绑定

如何在关联查询中指定外键

如何在关联查询中指定外键

牛魔王的故事 2021-06-01 22:46:02
当我进行包含另一个模型的查询时,如何指定外键,因为我有许多该模型的外键。DBTweet.findAll({ where: { userID: followingUserID }, include: [            { model: DBUser,         include: [                { model: DBFollower // Here i want to specify the foreign key },        ] },]})更新:当我与 as 有两个关联时用户多次与关注者相关联。要识别正确的关联,您必须使用“as”关键字来指定要包含的关联的别名DBFollower.findAll({ where: { followerUserID: req.params.userID }, include: [     { model: DBUser, attributes: { exclude: ['email', 'password', 'loginType', 'telephoneNumber'] }}]})这些是我的协会:DBUser.hasMany(DBTweet, { foreignKey: 'userID' }, { onDelete: 'cascade' })DBTweet.belongsTo(DBUser, {foreignKey: 'userID'}, { onDelete: 'cascade' })DBUser.hasMany(DBFollower, { as: 'followingUserIDAlias', foreignKey: 'followingUserID' }, { onDelete: 'cascade' })DBFollower.belongsTo(DBUser, { as: 'followingUserIDAlias', foreignKey: 'followingUserID' }, { onDelete: 'cascade' })DBUser.hasMany(DBFollower, { as: 'followerUserIDAlias', foreignKey: 'followerUserID' }, { onDelete: 'cascade' })DBFollower.belongsTo(DBUser, { as: 'followerUserIDAlias', foreignKey: 'followerUserID' }, { onDelete: 'cascade' })
查看完整描述

1 回答

?
青春有我

TA贡献1784条经验 获得超8个赞

DBTweet.findAll({ 

  where: { userID: followingUserID }, 

  include: [{ 

    model: DBUser,

    as: 'Users', //here goes the alias as well

    include: [{ 

      model: DBFollower, 

      as: 'Followers' //here is goes the alias of the association

    }],

  }]

});



module.exports = (sequelize, DataTypes) => {

  const DBUser = sequelize.define('DBUser', {

    // your attributes

  });


  DBUser.associate = (models) => {

    DBUser.hasMany(models.DBFollower,  {  as: 'Followers',  foreignKey: 'your_key' });

    // DBUser.belongsTo(models.DBFollower,  {  as: 'Followers',  foreignKey: 'branch_id' });

  };


  return DBUser;

};

更新:


现在与您的协会:


DBUser.hasMany(DBTweet, { as: 'Users', foreignKey: 'userID', onDelete: 'cascade' })

DBTweet.belongsTo(DBUser, { as: 'Users', foreignKey: 'userID', onDelete: 'cascade' })


DBUser.hasMany(DBFollower, { as: 'followingUserIDAlias', foreignKey: 'followingUserID', onDelete: 'cascade' })

DBFollower.belongsTo(DBUser, { as: 'followingUserIDAlias', foreignKey: 'followingUserID', onDelete: 'cascade' })


DBUser.hasMany(DBFollower, { as: 'followerUserIDAlias', foreignKey: 'followerUserID', onDelete: 'cascade' })

DBFollower.belongsTo(DBUser, { as: 'followerUserIDAlias', foreignKey: 'followerUserID', onDelete: 'cascade' })



查看完整回答
反对 回复 2021-06-03
  • 1 回答
  • 0 关注
  • 103 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信