GraphQL无法使查询正常工作
我有两个表类别和子类别定义为GraphQL无法使查询正常工作,graphql,knex.js,bookshelf.js,Graphql,Knex.js,Bookshelf.js,我有两个表类别和子类别定义为 CREATE TABLE `categories` ( `id` int(11) NOT NULL, `name` varchar(300) DEFAULT NULL, `image` varchar(300) DEFAULT NULL ); export const schema = ` type Category { id: ID name: String image: String subcategories : [SubCategory] }` 及
CREATE TABLE `categories` (
`id` int(11) NOT NULL,
`name` varchar(300) DEFAULT NULL,
`image` varchar(300) DEFAULT NULL
);
export const schema = `
type Category {
id: ID
name: String
image: String
subcategories : [SubCategory]
}`
及
此处子类别表中的cat字段是类别表中的id的外键
GraphQL模式定义为
CREATE TABLE `categories` (
`id` int(11) NOT NULL,
`name` varchar(300) DEFAULT NULL,
`image` varchar(300) DEFAULT NULL
);
export const schema = `
type Category {
id: ID
name: String
image: String
subcategories : [SubCategory]
}`
及
另外,Bookshelf.js中的DB模型如下
const Category = db.Model.extend({
tableName: 'categories',
subcats: function () {
return this.hasMany(SubCategory,"cat");
}
})
我的GraphQL查询如下
async getAllCategories() {
const allCats = await Category
.fetchAll()
.then(cats => {
return cats.toJSON()
})
return allCats
}
现在当我打电话的时候
{
getAllCategories {
id
name
subcategories {
id
name
}
}
}
我得到的回应是
{
"data": {
"getAllCategories": [
{
"id": "1",
"name": "usa",
"subcategories": null
},
{
"id": "2",
"name": "japan",
"subcategories": null
},
]
}
}
此处“子类别”字段为空,因为我想获取由外键cat在“子类别”表中连接的特定类别中的所有子类别。您必须急于加载子类别,因为它不是自动加载的:
const allCats = await Category
.fetchAll({withRelated: 'subcats'})
.then(cats => {
return cats.toJSON()
})
首先,您是如何让Bookshelf使用GraphQL的?您好,我随后仍然得到相同的错误。在这段代码中是否有最终的sql查询生成?我是否必须从类别表中获取每个id并在子类别表上循环?什么错误?你只提到没有子类别。您可以将
debug:true
选项传递给fetchAll
:.fetchAll({withRelated:'subcats',debug:true})
,以查看生成的SQL。