Lighthouse PHP多对多关联创建Post与Tag失败求助
问题解决步骤
1. 修正中间表关联配置
首先确保Post和Tag模型的belongsToMany关联定义正确,匹配你的中间表结构:
// app/Models/Post.php public function tags() { // 若中间表不是默认的post_tag,替换为实际表名;外键不符则修改后两个参数 return $this->belongsToMany(Tag::class, 'post_tag', 'post_id', 'tag_id'); } // app/Models/Tag.php public function posts() { return $this->belongsToMany(Post::class, 'post_tag', 'tag_id', 'post_id'); }
同时确认中间表已正确迁移,示例迁移代码:
Schema::create('post_tag', function (Blueprint $table) { $table->foreignId('post_id')->constrained()->onDelete('cascade'); $table->foreignId('tag_id')->constrained()->onDelete('cascade'); $table->primary(['post_id', 'tag_id']); });
2. 修正GraphQL输入格式错误
你的Mutation中create字段定义为数组类型,但传入的是单个对象,导致解析失败。修改后的正确Mutation:
mutation MyMutation { createPost( input: { channel_name: "Test6", create_date: "2023-08-26", source: "MY", tags: {create: [{name: "test55", color: "#ffffff"}]} } ) { id tags { id name } } }
注意create后的{}改为[],匹配Schema中[CreateTag!]的数组定义。
3. 修复connect功能
关联已有Tag时,connect字段需传入Tag的ID数组,示例:
mutation MyMutation { createPost( input: { channel_name: "Test6", create_date: "2023-08-26", source: "MY", tags: {connect: [1, 2]} } ) { id tags { id name } } }
也可混合使用create和connect,同时创建新标签并关联已有标签:
mutation MyMutation { createPost( input: { channel_name: "Test6", create_date: "2023-08-26", source: "MY", tags: { create: [{name: "test55", color: "#ffffff"}], connect: [1] } } ) { id tags { id name } } }
4. 检查模型可填充字段
确保Post和Tag模型的$fillable包含所有需要批量赋值的字段:
// app/Models/Post.php protected $fillable = ['source', 'channel_name', 'channel_img', 'name', 'create_date']; // app/Models/Tag.php protected $fillable = ['name', 'color', 'img'];
内容的提问来源于stack exchange,提问作者Straiker
相关产品推荐
相关产品推荐

