Eloquent updateOrCreate 未更新
Eloquent updateOrCreate not updating
我在使用 updateOrCreate 时遇到问题。
下面的代码成功地创建了一个新行;但是,当涉及到更新现有行时,它根本不起作用!
comm_helpful::updateOrCreate(
['ID' => 1],
['time' => 3000]
);
这完全符合预期:
comm_helpful::where('ID', 1)->update(['time' => 3000]);
我已将上面的示例精简到最低限度(这是我调试的一部分),但它仍然无法正常工作!
好的,几乎完全拔掉了我的头发;我发现 Eloquent 设置的问题:
protected $primaryKey = 'id';
用于更新方法并由 getKeyName() 返回。
protected function setKeysForSaveQuery(Builder $query)
{
$query->where($this->getKeyName(), '=', $this->getKeyForSaveQuery());
return $query;
}
然后我意识到我在故事中的 'id' 是大写而不是小写!
我想这意味着我的回答是我需要确保我使用小写 'id' 作为主键或在模型
上覆盖它
protected $primaryKey = 'ID';
我也有类似的问题。
我的模型有:
protected $fillable = ['user_x_cliente_id','internet_cliente_id'];
状态为0。
$habilita = leilao_habs::updateOrCreate(
[
'user_x_cliente_id' => $user_x_cliente->id,
'internet_cliente_id' => $int_cli->id
],
['status' => 1]
);
dd($habilita);
执行 updateOrCreate 后,status 仍然是 0,没有获取 MassAssignmentException 错误。
解决方案是更改模型,将状态添加到受保护的 $fillable:
protected $fillable = ['user_x_cliente_id','internet_cliente_id','status'];
现在 updateOrCreate 可以更改状态。
我在使用 updateOrCreate 时遇到问题。
下面的代码成功地创建了一个新行;但是,当涉及到更新现有行时,它根本不起作用!
comm_helpful::updateOrCreate(
['ID' => 1],
['time' => 3000]
);
这完全符合预期:
comm_helpful::where('ID', 1)->update(['time' => 3000]);
我已将上面的示例精简到最低限度(这是我调试的一部分),但它仍然无法正常工作!
好的,几乎完全拔掉了我的头发;我发现 Eloquent 设置的问题:
protected $primaryKey = 'id';
用于更新方法并由 getKeyName() 返回。
protected function setKeysForSaveQuery(Builder $query)
{
$query->where($this->getKeyName(), '=', $this->getKeyForSaveQuery());
return $query;
}
然后我意识到我在故事中的 'id' 是大写而不是小写!
我想这意味着我的回答是我需要确保我使用小写 'id' 作为主键或在模型
上覆盖它protected $primaryKey = 'ID';
我也有类似的问题。 我的模型有:
protected $fillable = ['user_x_cliente_id','internet_cliente_id'];
状态为0。
$habilita = leilao_habs::updateOrCreate(
[
'user_x_cliente_id' => $user_x_cliente->id,
'internet_cliente_id' => $int_cli->id
],
['status' => 1]
);
dd($habilita);
执行 updateOrCreate 后,status 仍然是 0,没有获取 MassAssignmentException 错误。
解决方案是更改模型,将状态添加到受保护的 $fillable:
protected $fillable = ['user_x_cliente_id','internet_cliente_id','status'];
现在 updateOrCreate 可以更改状态。