Laravel 灯塔 morphOne 突变

Laravel lighthouse morphOne mutation

我希望允许用户使用他们的 post 上传图像,但也能够允许用户通过 morphOne 关系为登陆页面上传图像。

我根据 laravel 文档设置我的模型,但如果需要可以提供它们。

与我的 schema.graphql 文件相比,我有以下内容

// schema.graphql

type Query

type Mutation



union Imageable = Blog | Landingspage


#import graphql/blog/*.graphql
#import graphql/landingspage/*.graphql
#import graphql/image/image.graphql

image.graphql 文件中我有以下内容

// image.graphql

extend type Mutation {
    createImage(input: ImageInput! @spread): Image @create
    updateImage(input: ImageInput! @spread): Image @update
    deleteImage(input: ImageInput! @spread): Image @delete
}

type Image {
    id: ID!
    url: String!
    imageable: Imageable! @morphTo
}

input ImageInput {
    id: ID!
    url: String
    imageable:ImageableMorphTo
}

input ImageableMorphTo {
    connect: ImageableInput
    disconnect: Boolean
    delete: Boolean
}

input ImageableInput {
    type: String!
    id: ID!
}

最后在我的 blog.graphql 文件中有这个

// blog.graphql

extend type Query {
    blogs: [Blog!]! @all  @orderBy(column: "created_at", direction: DESC)
    blog(slug: String! @eq): Blog @find
}

extend type Mutation {
    createBlog(input: CreateBlogInput @spread): Blog @create
}


type Blog {
    id: ID!
    title: String!
    big_text: String!
    small_text: String!
    slug: String!
    category_id: Int
    created_at: DateTime!
    updated_at: DateTime!
    image: Image @morphOne
}


input CreateBlogInput {
    title: String!
    big_text: String!
    small_text: String!
    category_id: Int,
    image: ImageInput
}

现在,当我去 graphql-playground 并创建突变时

mutation ($input: CreateBlogInput ){
  createBlog(input:$input){
    id
    title
    small_text
    big_text
    image{
      id
      url
    }
  }
}

使用以下输入

{
  "input": {
    "title": "image-test",
    "big_text": "big_text",
    "small_text": "small_text",
    "category_id": 2,
    "image": {
      "id": 3,
      "url": "https://cats.example/cute"
      }
    }
  }

我的回复是这样的

{
  "data": {
    "createBlog": {
      "id": "7",
      "title": "image-test",
      "small_text": "small_text",
      "big_text": "big_text",
      "image": null
    }
  }
}

如何使图像不再为空?我试图在

处对示例进行逆向工程

https://lighthouse-php.com/master/eloquent/nested-mutations.html#morphto

但这只向您展示了如何创建图像并将 post(或博客)连接到它,但我想创建一个带有图像的 post。

首先,如果您希望 image 字段不为空,只需添加一个 !,因此:

type Blog {
  # ...
  image: Image! @morphOne
}

其次,如果你想创建一个带有图片的博客,输入应该是这样的:

extend type Mutation {
    createBlog(input: CreateBlogInput @spread): Blog @create
}

input CreateBlogInput {
    title: String!
    big_text: String!
    small_text: String!
    category_id: Int,
    image: BlogImageRelationInput
}

input BlogImageRelationInput {
    upsert: UpsertImageInput
}

input UpsertImageInput {
    id: ID
    url: String
}