我有一些通过 belongsToMany 关系中的数据透视表关联的 Laravel 模型。
现在我尝试在 Laravel Lighthouse 中创建一个突变来加入模型并填充枢轴值。
不知何故,我无法找到如何做到这一点。
课程模型如下所示:
class Course extends Model
{
public function programs(): BelongsToMany
{
return $this->belongsToMany(\App\Models\Program::class, 'Course_Program')
->withPivot('id', 'year_id')
->withTimestamps();
}
}
我的 GraphQL 代码如下所示:
type Mutation {
createCourse(input: CreateCourseInput! @spread): Course! @create
}
type Course {
id: ID!
name: String!
programs: [ProgramWithPivot!]! @belongsToMany
}
type Program {
id: ID!
name: String!
}
type ProgramWithPivot {
id: ID!
name: String!
year_id: ID!
}
input CreateCourseInput {
name: String!
programs: CreateCourseProgramsRelation!
}
input CreateCourseProgramsRelation {
create: [CreateCourseProgramInput!]
}
input CreateCourseProgramInput {
id: ID!
year_id: ID!
}
问题是当我尝试在我的课程中创建这样的程序时:
mutation {
createCourse(input: {
name: "new cours"
programs: {
create: [{
id: 1
year_id: 2
}]
}
}) {
id
programs {
id
year_id
}
}
}
Laravel Lighthouse 尝试将数据插入Program表(并抱怨 Program.name 没有默认值)。
但是,我想将数据(course_id、year_id 和 program_id)插入Course_Program表。
如何告诉 Laravel Lighthouse 在数据透视表中插入数据?