亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何在關聯查詢中指定外鍵

如何在關聯查詢中指定外鍵

牛魔王的故事 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 關注
  • 125 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號