GraphQL查询Book.author字段报expected iterable错误的配置问题排查
问题根因排查
你遇到的报错是两个配置不匹配导致的:
1. GraphQL字段类型和关联类型不匹配
你在Book类型的Schema里将author字段定义为了[Author]数组类型,要求返回可迭代的集合,但你用的@belongsTo指令对应Eloquent的belongsTo关联,返回的是单个模型实例,不是可迭代对象,就触发了expected iterable的报错。
你把关联改成hasMany之后,hasMany返回的是模型集合(可迭代),和数组类型匹配,所以运行正常。
2. Eloquent关联参数逻辑错误
belongsTo方法的参数顺序为 (关联模型类, 当前表的外键字段, 关联表的主键字段),你现在写的参数是完全颠倒的:
// 你当前的写法逻辑是:用本模型(Book)的id字段,关联Author表的book_id字段 return $this->belongsTo('App\Models\Author', 'id', 'book_id');
从你给出的Author表结构有book_id字段来看,你的外键是存在Author表中的,这种情况Book对Author的关联本身就应该用hasOne(单作者)或者hasMany(多作者),而不是belongsTo。
修复方案
根据你的业务需求二选一即可:
方案A:一本书对应一个作者
- 修改Book的Schema,把
author字段从数组改为单个对象,关联指令保持@belongsTo,同时补上你查询用到的uuid字段避免后续报错:
type Book { id: ID! title: String # 去掉[],改为单个Author类型 author: Author @belongsTo(relation: "author") uuid: String }
- 给Book表新增
author_id外键字段,修改关联方法:
public function author() { return $this->belongsTo(\App\Models\Author::class, 'author_id', 'id'); }
方案B:一本书对应多个作者(兼容你现有表结构)
- 修改Book的Schema,把关联指令改为
@hasMany,同时补上uuid字段:
type Book { id: ID! title: String author: [Author] @hasMany(relation: "author") uuid: String }
- 关联方法保持你测试正常的
hasMany写法即可:
public function author() { return $this->hasMany('App\Models\Author', 'book_id', 'id'); }
内容的提问来源于stack exchange,提问作者oxygen
相关产品推荐
相关产品推荐

