sequelize 使用 include 在查询中指定连接键

sequelize specify join key in query with include

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

的相同字段 (id)

我想知道如何指定当我 select 用户与关联的 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 一个新的连接短语连接到主连接。

您需要在关联定义中使用 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',
});