gpt4 book ai didi

sequelize.js - 无法使用belongsToMany正确使用多对多

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

一段时间以来,我一直在试图解决这个问题。我读到 hasMany 在尝试建立 many-to-many 关联时不是正确的方法。我有两个表来创建以下关联 UserFollower (现在的名字很糟糕)。
追随者

const follower = (sequelize, DataTypes) => {
const Follower = sequelize.define('follower', {
follower_id: {
type: DataTypes.INTEGER,
allowNull: false,
validate: {
notNull: true
}
},
following_id: {
type: DataTypes.INTEGER,
allowNull: false,
validate: {
notNull: true
}
}
});

return Follower;
};

module.exports = follower;
接下来我们有 用户模型 作为
const user = (sequelize, DataTypes) => {
const User = sequelize.define('user', {
email: {
type: DataTypes.STRING,
unique: true,
allowNull: false,
validate: {
isEmail: true,
notEmpty: true
}
},
password: {
type: DataTypes.STRING,
allowNull: false,
validate: {
notEmpty: true
}
},
username: {
type: DataTypes.STRING,
unique: true,
allowNull: false
}
});

User.associate = (models) => {
User.hasMany(models.post, { foreignKey: 'user_id' });
User.belongsToMany(models.user, {
through: 'users_followers',
foreignKey: 'follower_id',
otherKey: 'following_id',
as: 'followers',
});
User.belongsToMany(models.user, {
through: 'users_followers',
foreignKey: 'following_id',
otherKey: 'follower_id',
as: 'following',
});

return User;
};

module.exports = user;
我在创建多对多关联方面做错了什么吗?我问是因为我一直在尝试差异变化,但在尝试 include: [db.follower] 时无法执行查询
谢谢大家的帮助
附加信息
正在运行的查询是:
const fetchUser = async (root, args, context) => {
const { db, user } = await context();
const { id } = args;

const fetchedUser = await db.user.findOne({
attributes: {
include: [
[sequelize.literal('(select count(*) from users_followers where users_followers.follower_id=users.id)'), 'followers_count'],
]
},
include: [
'followers',
'following'
],
where: {
id
},
raw: true
});

return fetchedUser;

最佳答案

include 选项中,您应该始终指示位于已定义关联另一侧的模型。在这种情况下,它是具有两个不同别名的 User 模型:

include: [
{
model: db.user,
as: 'followers'
}, {
model: db.user,
as: 'following'
}],

关于sequelize.js - 无法使用belongsToMany正确使用多对多,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65209668/

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