gpt4 book ai didi

node.js - 如何使用sequelize从graphql中的映射表中访问数据

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

我是 Sequelize 的新手,我有一个用户表、地址表和地址类型表,如下所示。
用户 可以有 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,
}

关于node.js - 如何使用sequelize从graphql中的映射表中访问数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61615411/

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