此代码运行正常。我现在可以得到追随者和追随者我需要看到我得到的追随者是我也跟着他们?
这是一个问题,我如何向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
仍然在续集中苦苦挣扎。
答案 0 :(得分:0)
将您的行查询转换为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
}
]
});