gpt4 book ai didi

sequelize.js - 当关系不使用主键时,将belongsToMany 序列化

转载 作者:行者123 更新时间:2023-12-03 22:41:28 24 4
gpt4 key购买 nike

我正在建立一个社交网络,所以我的模型是帖子、用户和用户-关注-用户关系

var User = sequelize.define('user', {
username: Sequelize.DataTypes.STRING
})

var Post = sequelize.define('post', {
text: Sequelize.DataTypes.STRING,
userId: Sequelize.DataTypes.INTEGER
})

var Follow = sequelize.define('follow', {
followerUserId: Sequelize.DataTypes.INTEGER,
followingUserId: Sequelize.DataTypes.INTEGER,
})

为了获取某个用户的提要 - 他们关注的用户的所有帖子 - 我需要能够执行如下所示的查询:
User.findById(13).then(user => user.getFollowingPosts())

但我被困在协会上:
User.belongsToMany(Post, {
as: 'followingPosts',
through: { model: Follow, },
foreignKey: 'followerUserId',
otherKey: 'userId',
});

生成错误的 SQL JOIN 条件,我无法修复:
SELECT ...
FROM `posts` AS `post` INNER JOIN `follows` AS `follow`
ON `post`.`id` = `follow`.`userId` AND `follow`.`followerUserId` = 13

我无法让用户 post.userId 而不是 post.id Sequelize

最佳答案

找到了一个足够好的解决方法:

Post.belongsTo(Follow, {
as: 'following',
foreignKey: 'userId',
targetKey: 'followingUserId',
allowNull: false
})

这样我完全跳过 User.blongsToMany 并查询以下信息:
Post.findAll({
include: [{
association: Post.associations.following,
where: { followerUserId: 13}
}]
})

产生:
SELECT ...
FROM `posts` AS `post` INNER JOIN `follows` AS `following`
ON `post`.`userId` = `following`.`followingUserId` AND
`following`.`followerUserId` = 13

关于sequelize.js - 当关系不使用主键时,将belongsToMany 序列化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43964333/

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