0

所以我一直在这个问题上撞墙,到目前为止我还没有找到解决方案。

我用最新的 Lighthouse(4.12) 创建了一个新鲜的、脆弱的 Laravel 项目,当我尝试按照文档进行操作时,我迷失了方向。

因此,根据文档,我制作了以下架构:

type Query {
    posts: [Post!]! @paginate(defaultCount: 10)
}

type Mutation {
  createPost(input: CreatePostInput! @spread): Post @create
}

input CreatePostInput {
  title: String!
  content: String
  images: CreateImageMorphToMany
}

input CreateImageMorphToMany {
  sync: [ID!]
  connect: [ID!]
}


type User {
    id: ID!
    name: String!
    email: String!
    created_at: DateTime!
    updated_at: DateTime!
    images: Image! @morphOne
}

type Post {
    id: ID!
    title: String
    content: String
    images: [Image]! @morphMany
}

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

union Imageable = Post | User

有以下课程:

后模型

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\MorphMany;

class Post extends Model
{

    protected $fillable = [
        'title', 'content'
    ];

    public function images(): MorphMany
    {
        return $this->morphMany('App\Image', 'imageable');
    }
}

图像模型

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\MorphTo;

class Image extends Model
{
    public function imageable(): MorphTo
    {
        return $this->morphTo();
    }
}


和迁移:

<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

class CreatePostsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('posts', function (Blueprint $table) {
            $table->id();
            $table->string('title');
            $table->string('content');
            $table->timestamps();
        });
        // This is only here for the sake of simplicity
        Schema::create('images', function (Blueprint $table) {
            $table->id();
            $table->string('src');
            $table->string('name');
            $table->integer('imageable_id');
            $table->string('imageable_type');
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('posts');
        Schema::dropIfExists('images');
    }
}

并使用提供的 GraphQL 操场,我希望以下突变:

mutation {
  createPost(input: {
    title: "asd", 
    content: "asd",
    images: {
      connect: [1]
    }

  }) {
    title
    images {
      src
    }
  }
}

将返回已创建帖子的连接/同步图像,但仅返回帖子。

但是,如果我手动设置关系并对其进行查询,则一切正常。

提前致谢!

4

1 回答 1

0

事实证明,我误解了文档(自从我提出问题以来一直在更新),因为 morphone 的工作原理与 hasone 完全一样,因此正确的方法是创建、删除、更新

于 2020-05-10T07:48:47.383 回答