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

当我进行包含另一个模型的查询时,如何指定外键,因为我有许多该模型的外键。


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' })


牛魔王的故事
浏览 104回答 1
1回答

青春有我

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' })
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript