我有2个表:用户和跟随者
基本架构如下:
var User = sequelize.define(
"User",
{
id: {
type: DataTypes.INTEGER,
autoIncrement: true,
primaryKey: true
},
username: DataTypes.STRING,
},
{
timestamps: true,
tableName: "users",
underscored: true
);
//Associations;
User.associate = function(models) {
User.hasMany(models.Follower, {
constraints: false,
onDelete: "cascade",
hooks: true
})
};
var Follower = sequelize.define(
"Follower",
{
id: {
type: DataTypes.INTEGER,
autoIncrement: true,
primaryKey: true
},
follower_id: {
type: DataTypes.INTEGER,
foreignKey: true
},
following_id: {
type: DataTypes.INTEGER,
foreignKey: true
}
},
{
timestamps: true,
tableName: "followers",
underscored: true
}
);
//Associations;
Follower.associate = function(models) {
Follower.belongsTo(models.User, {
foreignKey: "following_id",
constraints: false
}),
Follower.belongsTo(models.User, {
foreignKey: "follower_id",
constraints: false
});
};
我想获取用户的关注者列表,但我想向用户显示他们关注的对象,现在是他们自己的数据。
我当前正在运行此过程:
const following = await models.Follower.findAndCountAll({
attributes: models.Follower.fields,
where: { follower_id: user_id },
include:[
{
model: models.User,
attributes: models.User.fieldsPublic,
required: yes
}
]
})
问题在于include
返回的是当前用户,而不是他们关注的人的用户详细信息。
本质上,连接似乎在User.id
= Follower.follower_id
如何将其添加到include
并加入User.id
= Follower.following_id
答案 0 :(得分:0)
您既可以在模型定义中添加as
,也可以包括include以便定义应该使用哪个外键(docs)
也是这样:
Follower.associate = function(models) {
Follower.belongsTo(models.User, {
foreignKey: "following_id",
as: 'following',
constraints: false
}),
Follower.belongsTo(models.User, {
foreignKey: "follower_id",,
as: 'follower',
constraints: false
});
};
和
...
include:[
{
model: models.User,
attributes: models.User.fieldsPublic,
as: 'follower'
required: yes
}
]
...
或者,您可以删除required: yes
并使用where
属性定义连接条件
此外,include似乎有一个on
属性,据说该属性类似于where
(根据docs),但是我找不到一个示例。>