【问题标题】:GraphQL unable to get query workingGraphQL 无法让查询工作
【发布时间】:2019-01-12 12:48:51
【问题描述】:

我有两个表类别和子类别定义为

CREATE TABLE `categories` (
`id` int(11) NOT NULL,
`name` varchar(300) DEFAULT NULL,
`image` varchar(300) DEFAULT NULL
);

CREATE TABLE `sub_categories` (
`id` int(11) NOT NULL,
`name` varchar(45) DEFAULT NULL,
`cat` int(11) DEFAULT NULL,
`type` int(11) NOT NULL,
) 

这里 sub_categories 表中的 cat 字段是 categories 表中 id 的外键

GraphQL 架构定义为

export const schema = `
type Category {
id:    ID
name: String
image: String
subcategories : [SubCategory]
}`

type SubCategory {
id:    ID
name: String
cat: Int
type: Int
}

我在 Bookshelf.js 中的数据库模型也是

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
  },
 ]
 }
}

这里的 subcategories 字段为空,因为我想获取特定类别中的所有子类别,这些子类别通过 sub_categories 表中的外键 cat 连接。

【问题讨论】:

  • 您是如何让 Bookshelf 与 GraphQL 一起工作的?
  • 嗨,我关注了this guide

标签: graphql knex.js bookshelf.js


【解决方案1】:

您必须急切加载子类别,因为它不是自动的:

const allCats = await Category
  .fetchAll({withRelated: 'subcats'})
  .then(cats => {
    return cats.toJSON()
  })

【讨论】:

  • 仍然遇到同样的错误。无论如何要在此代码中显示最终的 sql 查询构建?我是否必须从类别表中获取每个 id 并遍历 sub_categories 表?
  • 什么错误?您只提到没有子类别。您可以将debug: true 选项传递给fetchAll.fetchAll({withRelated: 'subcats', debug: true}) 以查看生成的SQL。
猜你喜欢
  • 2016-07-10
  • 1970-01-01
  • 2012-04-22
  • 1970-01-01
  • 2011-03-28
  • 2017-11-18
  • 1970-01-01
  • 1970-01-01
  • 2018-06-28
相关资源
最近更新 更多