首页 > 解决方案 > 为什么 Laravel Lighthouse @rename 指令对我不起作用?

问题描述

我有这个 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 的 @rename 指令在大小写之间进行转换。然而,在运行查询时,在提交我的查询时,部分代码似乎无法识别项目 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 的外观,在 Budget 类型上使用 @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")
}

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

标签: graphqllaravel-lighthouse

解决方案


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

你的突变应该是这样的:

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

推荐阅读