Sequelize 非主键上的连接表

The*_*iwi 2 sql sql-server sequelize.js typescript angular

我的代码:

User.hasMany(UserMail, {foreignKey:'to_user_id', sourceKey:'id'});
User.hasMany(UserMail, {foreignKey:'from_user_id', sourceKey:'id'});

UserMail.belongsTo(User, {foreignKey: 'from_user_id'})
UserMail.belongsTo(User, {foreignKey: 'to_user_id'})

function getUserMail(req,res){
    // Authenticate
    jwt.verify(req.headers.jwt, process.env.JWT_KEY,function(err,decoded) {
        if (err) {
            return res.status(401).send("Invalid token");
        }
        let id = decoded.id;

        return UserMail.findAll({
            where: {
                to_user_id: id,
                to_user_deleted: false
            },
            include:{
              model: User,


              //This is where the error is
              on:{
                  id: Sequelize.where(Sequelize.col("User.id"), "=",Sequelize.col("UserMail.from_user_id"))
              },


                attributes:['username']
            },
            // attributes:[], // TODO Set what columns are needed
            order:[['id', 'DESC']]
        }).then(mail=> {
            return res.status(200).send(mail);
        })

    })
}
Run Code Online (Sandbox Code Playgroud)

当我使用它时,我得到“未处理的拒绝 SequelizeDatabaseError:缺少表“用户”的 FROM 子句条目”,我不确定这意味着什么。

我试过使用

where:{
    id: UserMail.from_user_id;
}
Run Code Online (Sandbox Code Playgroud)

但是每次执行查询时,它都有“User”.“id” = NULL,因此它永远不会返回结果。我还尝试了各种变体以使其不为 NULL,但我尝试过的变量均无效。

我只想向查询中添加一个列,即用户表中的用户名,其中 UserMail 表中的 from_user_id 位于用户表中。这听起来很简单,但我似乎一辈子都做不到。

只需使用即可在主键上加入表很简单

include:{[User]}
Run Code Online (Sandbox Code Playgroud)

它将包括 User 主键等于 UserMail 主键的位置,但这不是我想要的。我希望它在不是主键的 UserMail 列上。

Saa*_*ran 7

使用targetKey代替sourceKey

这是我项目中的代码,希望对您有所帮助

Country.hasMany(Region, { foreignKey: 'countrycode' })
Region.belongsTo(Country, { foreignKey: 'countrycode', targetKey:'countrycode' })
Run Code Online (Sandbox Code Playgroud)

所以,我们会

User.hasMany(UserMail, {foreignKey:'from_user_id'})
UserMail.belongsTo(User, {foreignKey: 'from_user_id', targetKey:'id'})
Run Code Online (Sandbox Code Playgroud)