使用 Graphql 和 Drupal 从多值字段获取数据

问题描述

我正在使用 Drupal graphql 模块从 Drupal 中公开我的数据。在检索简单数据(例如 id、作者或自定义字段)时,一切都很好。

我的问题是我有一个存储 25 个整数的字段。

我的类型定义:

type Card {
  id: Int!
  title: String
  author: String
  numbers: [Int]
}

我的字段解析器:

    $registry->addFieldResolver('Card','numbers',$builder->compose(
  $builder->produce('property_path')
  ->map('type',$builder->fromValue('entity:node:bingo_card'))
  ->map('path',$builder->fromValue('field_bingo_card_numbers'))
  ->map('value',$builder->fromParent()),),

);

除了数字之外,我完美地接收了所有数据。它返回 25 次 null 和如下错误

"extensions": [
    {
      "message": "Expected a value of type \"Int\" but received: {\"value\":\"27\"}",

所以问题是返回了 25 个对象(?),而不是多值字段中每个项目的值。

如果我尝试:

->map('path',$builder->fromValue('field_bingo_card_numbers.value'))

错误变为:

 "message": "User Error: expected iterable,but did not find one for field Card.numbers.",

现在只为数字返回 1 次 null,而不是为每个数字返回 null

大家有什么建议吗?

解决方法

您需要在“compose”中添加类似以下内容

$builder->callback(function ($entity) {
  $list = [];
  foreach($entity as $item){
    array_push($list,$item['value']);
  }
  return $list;
})