新しいアプリの GraphQL API を作成するために Laravel Lighthouse を使用していますが、Nested Belongs to および Belongs to Many が create および update メソッドで機能せず、ピボット テーブルで何も追加されず、次のエラーが発生します。
"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);
}
}
タグ モデル:
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!]
}
誰が問題が何であるか知っていますか?