Laravel Вложенные мутации Lighthouse не работают - PullRequest
0 голосов
/ 04 мая 2020

Я использую Laravel Lighthouse для создания API-интерфейсов GraphQL для моего нового приложения, и теперь «Вложенный принадлежит» и «Принадлежит многим», не работает метод создания и обновления, в сводной таблице ничего не добавлено, и я получаю следующую ошибку :

"SQLSTATE[HY000]: General error: 1364 Field 'category_id' doesn't have a default value (SQL: insert into `products` (`title`, `updated_at`, `created_at`) values (new product, 2020-05-03 19:40:59, 2020-05-03 19:40:59))"

Миграция продукта:

public function up()
    {
        Schema::create('products', function (Blueprint $table) {
            $table->id();
            $table->string('title');
            $table->unsignedBigInteger('category_id');
            $table->foreign('category_id')->references('id')->on('categories')->onDelete('cascade');
            $table->integer('status')->default(1);
            $table->softDeletes();
            $table->timestamps();
        });
    }

Миграция тега:

public function up()
    {
        Schema::create('tags', function (Blueprint $table) {
            $table->id();
            $table->string('title');
            $table->unsignedBigInteger('category_id');
            $table->foreign('category_id')->references('id')->on('categories')->onDelete('cascade');
            $table->integer('status')->default(1);
            $table->softDeletes();
            $table->timestamps();
        });
    }

Миграция сводки:

public function up()
    {
        Schema::create('product_tag', function (Blueprint $table) {
            $table->id();
            $table->unsignedBigInteger('product_id');
            $table->foreign('product_id')->references('id')->on('products')->onDelete('cascade');
            $table->unsignedBigInteger('tag_id');
            $table->foreign('tag_id')->references('id')->on('tags')->onDelete('cascade');
            $table->timestamps();
        });
    }

Модель продукта:

class Product extends Model
{
    use SoftDeletes;

    protected $fillable = [
        'title', 'category_id', 'status'
    ];

    public function category()
    {
        return $this->belongsTo(Category::class);
    }

    public function tags()
    {
        return $this->belongsToMany(Tag::class);
    }
}

Tag Model:

class Tag extends Model
{
    use SoftDeletes;

    protected $fillable = [
        'title', 'category_id', 'status'
    ];

    protected static function booted()
    {
        static::deleted(function ($tag) {
           $tag->products()->detach();
        });
    }

    public function category()
    {
        return $this->belongsTo(Category::class);
    }

    public function products()
    {
        return $this->belongsToMany(Product::class);
    }
}

Схема продукта

extend type Query @guard(with: ["sanctum"]) {
    products(orderBy: _ @orderBy trashed: Trashed @trashed): [Product] @all
}

extend type Mutation @guard(with: ["sanctum"]) {
    createProduct(
        title: String! @rules(apply: ["required"])
        category: CreateCategoryRelation
        tags: UpdateProductTags
    ): Product @create

    updateProduct(
        id: ID!
        title: String! @rules(apply: ["required"])
        category: CreateCategoryRelation
        tags: UpdateProductTags
    ): Product @update

    deleteProduct(
        id: ID!
    ): Product @delete
}

type Product {
    id: ID!
    title: String!
    category: Category!
    tags: [Tag!]
}

input CreateCategoryRelation {
    connect: ID!
}

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

Кто-нибудь знает в чем проблема?

1 Ответ

0 голосов
/ 04 мая 2020

Я нашел решение, Lighthouse использует подсказку типа, чтобы определить, как он должен обрабатывать отношения.

use Illuminate\Database\Eloquent\Relations\BelongsTo;

class Post extends Model 
{
    // WORKS
    public function user(): BelongsTo
    {
        return $this->belongsTo(User::class);
    }

    // DOES NOT WORK
    public function comments()
    {
        return $this->hasMany(Comment::class);        
    }
}
...