Laravel Lighthouse使用morphOne创建Blog时关联Image为空如何解决
问题解决方案
你遇到的问题是创建Blog时嵌套关联morphOne的Image逻辑未生效,按以下步骤修改即可:
1. 开启嵌套变更支持
Lighthouse默认不会自动处理@create/@update指令下的嵌套关联,需要显式声明要处理的嵌套字段。修改blog.graphql中的createBlog mutation定义:
extend type Mutation { createBlog(input: CreateBlogInput @spread): Blog @create(nested: ["image"]) }
2. 调整输入结构适配关联操作
你的原有CreateBlogInput中image字段的类型不符合嵌套关联的约定,需要调整为支持connect(关联已有图片)或create(创建博文同时新建图片)的结构:
input CreateBlogInput { title: String! big_text: String! small_text: String! category_id: Int, image: BlogImageOperationInput } # 定义图片关联操作的输入类型 input BlogImageOperationInput { # 关联已有图片时传对应图片ID connect: ID # 新建图片时传对应的图片参数 create: NewImageInput } # 新建图片的参数定义 input NewImageInput { url: String! }
你原有ImageInput中设置的id: ID!是错误的,创建新图片时ID自动生成不需要传入,仅更新/删除操作需要必填ID
3. 修改请求参数格式
根据你的需求选择对应的参数格式:
场景1:创建博文时关联已经存在的图片
{ "input": { "title": "image-test", "big_text": "big_text", "small_text": "small_text", "category_id": 2, "image": { "connect": 3 } } }
场景2:创建博文时同时新建图片并关联
{ "input": { "title": "image-test", "big_text": "big_text", "small_text": "small_text", "category_id": 2, "image": { "create": { "url": "https://cats.example/cute" } } } }
4. 确认底层配置正确
- 确认
Blog模型中已定义正确的morphOne关联:
public function image() { return $this->morphOne(Image::class, 'imageable'); }
- 确认
Image模型中已定义正确的morphTo关联:
public function imageable() { return $this->morphTo(); }
- 确认
images数据表中存在imageable_id、imageable_type两个字段,类型与关联模型匹配。
完成以上修改后再次请求,image字段即可正常返回关联数据。
内容的提问来源于stack exchange,提问作者niels van hoof
相关产品推荐
相关产品推荐

