如果我错了,请纠正我。
我有两个模型 "用户 "和 "配置文件"
场景1。
在 "Profiles "模型中,我将 "user_id "定义为主键,外键为 "user.id"
class Profile extends Model
{
/**
* primary key
*/
protected $primaryKey = 'user_id';
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = [
'user_id', 'country'
];
在schema.graphql
type Mutation {
upsertProfile(user_id: ID, country: String): Profile @upsert
}
type Profile {
user_id: ID!
country: String
user: User @belongsTo
}
假设有一个id 28 中的用户表。当我尝试运行突变。
mutation {
upsertProfile(user_id: 28, country: "India") {
country
}
}
它能正常运行并更新国家,但如果没有user_id的话 28 存在,按照定义它应该创建一个。
因为它定义了 user_id列不是一个自动递增的列。
我又做了一次测试
场景2.我删除了'user_id'作为主键,并添加了id列作为主键,然后将其作为主键。
我删除了 "user_id "作为主键,并添加了id列作为主键,然后... 自动递增. 假设id1在那里,那么运行突变后,我得到了预期的结果。
mutation {
upsertProfile(id: 1, country: "India") {
country
}
}
我得到了预期的结果,但是当我尝试运行突变时
mutation {
upsertProfile(user_id: 28, country: "India") {
country
}
}
每当我运行这个突变时,我每次都会得到带有新id的重复结果(自动增加)。
我的问题是
如何使用upsert,如果user_id存在,则更新行,否则创建行。
由于laravel的createOrUpdate函数原型包含了对多个列的检查以获得更新的行,有没有什么方法可以在upsert指令上做同样的事情。
另外, 在 场景1 我对查询进行了调试,发现插入查询正在运行,但在grpahql-playground结果处出现异常。
{
"errors": [
{
"debugMessage": "No query results for model [App\\Models\\Profile] 0",
"message": "Internal server error",
"extensions": {
"category": "internal"
},
"locations": [
{
"line": 2,
"column": 3
}
],
"path": [
"upsertProfile"
],
....
]
确保ID属性是可填充的unguarded。