node.js - 如何使用 sequelize 从 graphql 中的映射表中访问数据
问题描述
我是续集的新手,我有一个用户表、地址表和地址类型表,如下所示。一个用户可以有 2 个不同的地址,永久地址和当前地址,地址类型(永久或当前)在表地址类型中指定。
我试图从基于模式的解析器中的映射表(address_type)访问数据并从 user -> address table 设置hasMany关系,但 graphql 显示未找到关联错误。我们如何才能正确获取关系以获取映射地址类型名称。
type User{
id:Int
name:String
}
type Address {
id: ID!
user_id:Int
city: String
addr_type:AddressType
}
type AddressType{
id : Int
name:String (permanent|current)
}
表定义
module.exports = function(sequelize, DataTypes) {
return sequelize.define('user', {
id: {
type: DataTypes.INTEGER, allowNull: false, primaryKey: true, autoIncrement: true
},
name: {
type: DataTypes.INTEGER, allowNull: false,
},
}, {
tableName: 'user',
timestamps: false
});
};
module.exports = function(sequelize, DataTypes) {
return sequelize.define('address', {
id: {
type: DataTypes.INTEGER, allowNull: false, primaryKey: true, autoIncrement: true
},
user_id: {
type: DataTypes.INTEGER, allowNull: false, field:"addr_type"
},
addr_type: {
type: DataTypes.INTEGER, allowNull: false, field:"addr_type"
},
city: {
type: DataTypes.STRING, allowNull: false,
},
}, {
tableName: 'address',
timestamps: false
});
};
module.exports = function(sequelize, DataTypes) {
return sequelize.define('address_types', {
id: {
type: DataTypes.INTEGER, allowNull: false, primaryKey: true, autoIncrement: true
},
name: {
type: DataTypes.STRING, allowNull: false,
},
}, {
tableName: 'address_type',
timestamps: false
});
};
关系
db.user.hasMany(db.address,{foreignKey: 'user_id'});
db.address.belongsTo(db.user,{foreignKey: 'user_id'});
db.address.belongsTo(db.address_types,{foreignKey: 'addr_type'});
解析器代码
userts: async (obj, args, context, info ) => User.findAll( {
where: { user_status: 1 },
,
raw: true,
nest: true,
} ).then(userts => {
const response = userts.map(usert => {
return{
// i have 15 fields for a user, if i can access the schema of the corresponsing resolver i can dynamically build the response out put
id: usert.id,
firstName: usert.firstName,
lastName: usert.lastName,
middleName: usert.middleName,
}
})
return response;
}),
解决方案
您应该关闭选项raw以获取关联对象并使用include选项指示您希望加载的关联模型。
User.findAll( {
where: { user_status: 1 },
include: [{
model: Address,
include: AddressType
}],
raw: false,
nest: true,
}
推荐阅读
- c++ - C++ 转换为“叔叔班”
- javascript - Promise 中的比较表达式总是返回 true
- java - 提供者 com.levigo.jbig2.util.log.JDKLoggerBridge 不是子类型
- c# - C#如何从bindingSource中删除不断更新的项目(数据)
- c# - 具有复杂类型集合的 C# odata 操作失败
- c - ASM 到 C:如何取消引用指针并添加偏移量?
- javascript - 如何在 React 中使用新的功能挂钩?
- python - 将 PI 计算到许多小数位的进度指示器
- vb6 - 在 Visual Basic 6 中为标签生成随机非重复颜色
- git - 在私有仓库中管理多个上游 git 子模块 URL