我需要加入(1:1)2个模型并将其解析为graphql。
为PartsList和Items定义的模型:
const Item = sequelize.define('Item', {
id: {
type: DataTypes.INTEGER,
primaryKey: true,
autoIncrement: true
},
itemNumber: {
type: DataTypes.TEXT,
allowNull: false
},
title: {
type: DataTypes.TEXT,
allowNull: false,
},
description: {
type: DataTypes.TEXT,
allowNull: true
},
stock: {
type: DataTypes.INTEGER,
allowNull: false
},
},
);
const PartsList = sequelize.define('PartsList', {
id: {
type: DataTypes.INTEGER,
primaryKey: true,
autoIncrement: true
},
parentId: {
type: DataTypes.INTEGER,
allowNull: true
},
itemNo: {
type: DataTypes.INTEGER,
allowNull: false
},
quantity: {
type: DataTypes.INTEGER,
allowNull: false
},
itemId: {
type: DataTypes.INTEGER,
}
},
);
PartsList.associate = (models) => {
PartsList.belongsTo(models.Item, { as: 'item'});
}
零件列表的项目模式:
const typeDefs = gql`
type Item {
id: ID!
itemNumber: String!
title: String!
description: String
stock: Int!
}
extend type Query {
item(id: ID!): Item
itemNo(itemNumber: String!): Item
items: [Item!]!
}
extend type Mutation {
createItem(input: ItemInput!): Item!
updateItem(input: ItemInput!): Item!
deleteItem(input: ItemInput!): Item!
}
`;
const typeDefs = gql`
type PartsList {
id: ID!
parentId: Int
itemNo: Int!
quantity: Int!
itemId: Item
}
extend type Query {
partsList(id: ID!): PartsList
partsLists: [PartsList!]!
}
`;
以下SQL查询满足了我的请求:
选择p.id,p.parentId,p.itemNo,p.quantity,i.itemNumber,i.title来自PartsList AS p加入项目AS i ON p.itemId = i.id;
id parentId itemNo quantity itemNumber title
2 NULL 1 1 512526 Item A
3 2 1 1 123456 Item B
4 2 1 2 234567 Item C
我正在寻找查询和解析器
query {
xyz {
id // from partsList
parentId // from partsList
itemNo // from partsList
quantity // from partsList
itemNumber // from Item
description // from Item
}
}
获得所需的结果
{
"data":{
"partsList":[
{
"id": "2", // from partsList
"parentId": null, // from partsList
"itemNo": "1", // from partsList
"quantity": "1", // from partsList
"itemNumber": "512526", // from Item
"description": "Item A",// from Item
},
{
...
},
{
...
}
]
}
}
感谢帮助