【问题标题】:Sequelize join tables on non primary key在非主键上对连接表进行 Sequelize
【发布时间】:2018-03-29 19:29:48
【问题描述】:

我的代码:

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:缺少表“用户”的 FROM 子句条目”,我不确定这是什么意思。

我尝试过使用

where:{
    id: UserMail.from_user_id;
}

但是每次执行查询时,它都有 "User"."id" = NULL 所以它永远不会返回结果。我还尝试了各种变体以使其不为 NULL,但我尝试过的变量没有工作。

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

使用主键加入表很简单

include:{[User]}

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

【问题讨论】:

    标签: sql sql-server angular typescript sequelize.js


    【解决方案1】:

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

    所以把sourceKey改成你想要的列。

    【讨论】:

      【解决方案2】:

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2016-10-15
        • 1970-01-01
        • 2017-05-22
        • 1970-01-01
        • 2015-06-15
        • 2013-11-07
        • 1970-01-01
        相关资源
        最近更新 更多