我正在努力理解如何通过灯塔建立关系。假设我有一个Post
模型。在我的,我有:belongsTo
User
schema.graphql
type Mutation {
createPost(input: CreatePostInput! @spread): Post! @create
}
input CreatePostInput! {
text: String!
user: BelongsToUser!
}
input BelongsToUser {
connect: ID!
}
我在数据库中的 Post 对象有一个外键列user_id
当我运行查询时:
mutation {
createPost(input: {
text: "Hello World",
user: {
connect: 1
}
}){
id
}
}
我收到一个错误:Field 'user_id' doesn't have a default value
我觉得我做错了什么,这个突变没有更新关系的正确列,有人可以指出我可能做错了什么吗?(如果我在数据库中使用默认值使列可以为空,它会被插入,但关系当然是不正确的。我还可以调整 graphql 模式以使用user_id: Int
它确实有效但感觉做事的方式是错误的。)
一切都通过 Eloquent 正常工作,并且 graphql 查询正常工作,正确拉入相关对象。
注意:根据文档,我在模型中定义了关系的返回类:
class Post extends Model
{
public function user(): BelongsTo
{
return $this->belongsTo(User::class);
}
}
以及相关的迁移:
Schema::create('posts', function (Blueprint $table) {
$table->id();
$table->foreignId('user_id')->constrained();
$table->string('text');
...