gpt4 book ai didi

mysql - 如何使用以下和跟随者示例在 sequelize 中加入两次单个表

转载 作者:可可西里 更新时间:2023-11-01 07:43:27 24 4
gpt4 key购买 nike

这段代码运行完美。我现在可以获得关注和关注者,我需要查看我获得的关注者是否也在关注他们?

问题是我如何对 Followers 表进行另一个查询/子查询并查看我是否也在关注我的关注者。

追随者表

export default function(sequelize, DataTypes) {
return sequelize.define('Follower', {
_id: {
type: DataTypes.INTEGER,
allowNull: false,
primaryKey: true,
autoIncrement: true
},
userId: {
type: DataTypes.INTEGER,
allowNull: false
},
followingId: {
type: DataTypes.INTEGER,
allowNull: false
}
});
}

协会

db.Follower.belongsTo(db.User, {as:'following', foreignKey: 'followingId'});
db.Follower.belongsTo(db.User, {as:'follower', foreignKey: 'userId'});

查询

Follower.findAll({
where: {
followingId: userId
},
attributes: ['_id'],
include: [
{
model: User,
attributes: ['fullName', 'username', '_id', 'picture'],
as: 'follower'
}
]
})

更新

我已经从行查询中获得了期望的结果:

SELECT  F.userId, F.`followingId` , F1.`followingId` as IsFollowing , U.`fullName` FROM Followers as F

INNER JOIN Users as U ON userId = U._id

LEFT JOIN Followers as F1 On F.userId = F1.followingId

WHERE F.followingId = 142

仍在 Sequelize 中挣扎。

最佳答案

将您的行查询转换为 sequlize 请求试试这个:

协会

db.Follower.belongsTo(db.User, {as: 'following', foreignKey: 'followingId', sourceKey: 'userId'});
db.Follower.hasOne(db.User, {as: 'follower', foreignKey: 'userId'});

查询

Follower.findAll({
where: {
followingId: userId
},
attributes: ['userId', 'followingId'],
include: [
{
model: User,
attributes: ['fullName'],
as: 'follower',
required: true // to get inner join
},
{
model: Follower,
attributes: [['followingId', 'IsFollowing']],
as: 'following',
required: false // to get left join
}
]
});

关于mysql - 如何使用以下和跟随者示例在 sequelize 中加入两次单个表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46144444/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com