Sequelize在非主键上连接表

4

我的代码:

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

    })
}

当我使用它时,出现了“未处理的拒绝SequelizeDatabaseError:缺少“User”表的FROM条目”,我不确定这是什么意思。
我尝试使用

,但它没有解决问题。
where:{
    id: UserMail.from_user_id;
}

但是每次执行查询时,它的 "User"."id" 均为 NULL,因此从未返回结果。我也尝试了各种变化来使其不为空,但我尝试过的任何变量都不起作用。
我只想在查询中添加一个列,即 Users 表中的用户名,其中 UserMail 表中的 from_user_id 在 Users 表中。听起来很简单,但我似乎无法做到。
仅使用主键加入表格非常简单。
include:{[User]}

这段代码涉及到IT技术,其中包含了关于用户主键等于UserMail主键的内容,但这不是我想要的。我希望它适用于一个不是主键的UserMail列。

3个回答

13

请使用targetKey代替sourceKey

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

Country.hasMany(Region, { foreignKey: 'countrycode' })
Region.belongsTo(Country, { foreignKey: 'countrycode', targetKey:'countrycode' })

所以,你的将会是

User.hasMany(UserMail, {foreignKey:'from_user_id'})
UserMail.belongsTo(User, {foreignKey: 'from_user_id', targetKey:'id'})

2

我个人的方法是同时收集“targetKey”和“sourceKey”,如下所示:

TableB.belongsTo(models.TableA, { foreignKey: 'someID', targetKey: 'notTableAID' } );

TableA.hasOne(TableB, {
  sourceKey: 'NonPrimaryKeyColumnOnTheSourceModel',
  foreignKey: 'matchingColumnOnTheTargetModel'
});


-1

{sourceKey: 'id'}: UserMail.id 将被添加到 User 表中作为外键列的内容。

因此,将 sourceKey 更改为您想要的列名即可。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接