【问题标题】:Why does the Laravel Lighthouse @rename directive not work for me?为什么 Laravel Lighthouse @rename 指令对我不起作用?
【发布时间】:2020-03-27 23:30:17
【问题描述】:

我有这个 GraphQL 查询:

mutation CreateBudget(
  $revenue: Float!,
  $hours: Int!,
  $projectId: Int!,
) {
  createBudget(
    revenue: $revenue,
    hours: $hours,
    projectId: $projectId,
  ) {
    id
  }
}

为了获得最佳实践,我想在这里使用 camelcase,但在我的数据库中使用 snake_case。表格如下所示:

CREATE TABLE IF NOT EXISTS `budgets` (
  `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `revenue` double(8,2) NOT NULL,
  `hours` int(11) NOT NULL,
  `project_id` int(10) unsigned NOT NULL,
  `created_at` timestamp NULL DEFAULT NULL,
  `updated_at` timestamp NULL DEFAULT NULL,
  PRIMARY KEY (`id`),
  KEY `budgets_project_id_foreign` (`project_id`),
  CONSTRAINT `budgets_project_id_foreign` FOREIGN KEY (`project_id`) REFERENCES `projects` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

我使用Lighthouse's @rename directive 在外壳之间进行转换。然而,在运行查询时,在提交我的查询时,部分代码似乎无法识别项目 ID,从而导致以下 SQL 错误:

SQLSTATE[HY000]: General error: 1364 Field 'project_id' doesn't have a default value (SQL: insert into `budgets` (`revenue`, `hours`, `updated_at`, `created_at`) values (1200, 12, 2019-12-03 09:12:13, 2019-12-03 09:12:13))

发送的变量是

variables: {
    revenue: 1200,
    hours: 12,
    projectId: 1
}

这是我的 schema.graphql 的外观,在预算类型上使用 @rename 指令:

type Budget {
  id: ID!
  revenue: Float!
  hours: Int!
  projectId: Int! @rename(attribute: "project_id")
  project: Project! @belongsTo
  created_at: DateTime
  updated_at: DateTime
}

type Mutation {
    createBudget(
        revenue: Float!
        hours: Int!
        projectId: Int!
    ): Budget @create(model: "App\\Models\\Budget\\Budget")
}

我一定忽略了一些简单的事情,但我似乎无法发现它。有人想试一试吗?

【问题讨论】:

  • 不确定是否相关,但project_id 是否可以在模型中填写?
  • project_id 确实是可填充的,所有其他属性也是如此。

标签: graphql laravel-lighthouse


【解决方案1】:

从 4.7 版开始支持对突变使用重命名指令,并且需要在突变中的属性上额外声明重命名指令。

你的变异应该是这样的:

type Mutation {
    createBudget(
        revenue: Float!
        hours: Int!
        projectId: Int! @rename(attribute: "project_id")
    ): Budget @create(model: "App\\Models\\Budget\\Budget")
}

【讨论】:

  • 这两种情况你都错了。对突变使用重命名指令也不起作用。此外,docs mention @rename in version 2.6 已经存在,所以我认为我不需要使用 master。顺便说一句,我使用的是 v4.6。
  • 是的,@rename 指令很久以前就存在了,但就在几天前,它被更改为也可以与输入一起使用(在它只在类型字段中工作之前)。见公关:github.com/nuwave/lighthouse/pull/1062
  • 这不会改变任何事情,因为我是在 Type 而不是 Input 上定义我的 @rename。
  • 显然在类型上声明重命名指令只会影响查询而不影响突变。直接在突变上再次使用重命名指令将解决这个问题,但仅限于 v4.7(昨天才发布)。然而,我发现这个双重声明很奇怪,submitted an issue
猜你喜欢
  • 2020-12-21
  • 2016-10-03
  • 1970-01-01
  • 1970-01-01
  • 2019-05-18
  • 2013-08-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多