问题描述:
在使用Apollo和Sequelize进行开发时,当使用belongsTo
关联模型时,关联返回的结果为null。
解决方法:
首先,确保已正确设置了模型之间的关联。在Sequelize中,使用belongsTo
方法定义模型之间的关联关系。
接下来,检查数据库中的数据是否符合关联条件。如果关联的外键在关联模型中不存在,关联查询将返回null。
然后,确保在查询关联模型时使用了正确的关联条件。在Sequelize中,可以使用include
选项将关联模型加载到查询结果中。
下面是一个示例代码,演示了如何使用Apollo和Sequelize创建简单的belongsTo
关联关系:
// 定义模型
const User = sequelize.define('User', {
name: DataTypes.STRING
});
const Post = sequelize.define('Post', {
title: DataTypes.STRING,
content: DataTypes.TEXT
});
// 定义关联关系
Post.belongsTo(User, { foreignKey: 'userId' });
User.hasMany(Post, { foreignKey: 'userId' });
// 查询数据
const getUserWithPosts = async (userId) => {
try {
const user = await User.findOne({
where: { id: userId },
include: Post
});
console.log(user);
} catch (error) {
console.error(error);
}
};
// 调用查询函数
getUserWithPosts(1);
在上面的示例中,Post
模型通过belongsTo
关联到User
模型,并通过foreignKey
指定外键名为userId
。然后,User
模型通过hasMany
关联到Post
模型,也使用foreignKey
指定外键名为userId
。
在getUserWithPosts
函数中,我们通过调用User.findOne
查询指定userId
的用户,并使用include
选项加载关联的Post
模型。最后,打印查询结果。
确保数据库中存在符合关联条件的数据,并正确设置了模型之间的关联关系,在调用getUserWithPosts
函数时,应该能够正确返回关联结果。