为什么Laravel Lighthouse @rename指令对我不起作用?

时间:2019-12-03 09:57:45

标签: graphql laravel-lighthouse

我有这个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的外观,使用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")
}

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

1 个答案:

答案 0 :(得分:1)

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

您的突变应如下所示:

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