Laravel graphql Upsert指令未按预期工作



如果我错了,请纠正我。

我有两个模型"用户"one_answers"配置文件">

场景1:

在"Profiles"模型中,我将"user_id"定义为主键,并将外键定义为"users.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
}

假设users表中有一个id28。当我尝试运行突变:

mutation {
upsertProfile(user_id: 28, country: "India") {
country
}
}

它工作正常,并更新国家/地区,但如果不存在user_id28,根据定义,它应该创建一个。

由于定义了,user_id列不是自动递增列

我又做了一次测试

场景2:

我删除了"user_id"作为主键,并添加了id列作为主键和自动递增。假设id 1在那里,那么在运行突变之后:

mutation {
upsertProfile(id: 1, country: "India") {
country
}
}

我得到了预期的结果。但当我尝试运行突变时

mutation {
upsertProfile(user_id: 28, country: "India") {
country
}
}

每当我运行这个突变时,我每次都会得到带有新id的重复结果(自动递增(。

我的问题,

  1. 如果user_id存在,如何使用upstart,然后更新行,否则创建一行。

  2. 由于laravel createOrUpdate函数原型包含对多个列进行检查以更新一行,因此有没有任何方法可以对upstart指令执行同样的操作。

BTW,在场景1中,我调试了查询,发现插入查询正在运行,但我在grpahql游乐场结果中遇到异常

{
"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属性是可填充/不可保护的。

在我的案例中,这是一个时间戳问题。我把这行代码放在我的模型中,解决了问题

public $timestamps = false;

最新更新