【问题标题】:sequelize specify join key in query with includesequelize 在查询中使用包含指定连接键
【发布时间】:2016-01-09 19:29:27
【问题描述】:

我有两个模型 user_auth 和 user_follow。这样 2 个 user_follow 字段(follower_id 和 followee_id)引用 user_auth 的相同字段(id)。

我想知道如何指定当我选择具有关联 user_follow 的用户时将使用的加入条件,他是被关注者。我有这个代码:

userAuth.findOne({
        where:{
            id: data.viewee_id
        },
        include: [{
            model: userFollow,
            required: false,
            attributes: ["id"]
        }]
    })

这样的连接子句的查询结果:

FROM
`user_auth` AS `user_auth`
LEFT OUTER JOIN
`user_follow` AS `user_follow`
ON
`user_auth`.`id` = `user_follow`.`followee_id`

我不知道在哪里指定连接键。我的怀疑是因为我的 user_follow 定义为:

classMethods: {
    associate: function(models) {
        userAuth.hasOne(models.user_follow, {
            onDelete: "CASCADE",
            onUpdate: "CASCADE",
            foreignKey: 'follower_id',
            targetKey: 'id',
        });

        userAuth.hasOne(models.user_follow, {            
            onDelete: "CASCADE",
            onUpdate: "CASCADE",
            foreignKey: 'followee_id',
            targetKey: 'id',
        });
    }
},

根据实际测试,是后者hasOne造成的。如果我删除它,查找查询将使用 follower_id 作为连接键。

是否可以在查询中指定连接键?因为否则我未来的查询将受到模型定义的约束。

PS:我知道我可以在我的包含中添加一个 where 键,但它只是通过 AND 将一个新的连接短语连接到主连接。

【问题讨论】:

    标签: sequelize.js


    【解决方案1】:

    您需要在关联定义中使用as 选项指定别名。请参阅docs

    userAuth.hasOne(models.user_follow, {
      as: 'Follower',
      onDelete: "CASCADE",
      onUpdate: "CASCADE",
      foreignKey: 'follower_id',
      targetKey: 'id',
    });
    
    userAuth.hasOne(models.user_follow, {            
      as: "Followee",
      onDelete: "CASCADE",
      onUpdate: "CASCADE",
      foreignKey: 'followee_id',
      targetKey: 'id',
    });
    

    【讨论】:

      猜你喜欢
      • 2019-01-27
      • 2016-12-13
      • 2015-10-12
      • 1970-01-01
      • 2017-02-11
      • 2023-04-01
      • 2017-03-30
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多