我在使用 updateOrCreate 时遇到了麻烦。
下面的代码正在成功地创建一个新行,但是在更新现有行时,它根本不起作用!
comm_helpful::updateOrCreate(
['ID' => 1],
['time' => 3000]
);
这正如我们所预料的那样:
comm_helpful::where('ID', 1)->update(['time' => 3000]);
我已经将上面的示例剥离到最低限度(这是调试的一部分) ,但它仍然不能工作!
Ok, after almost completely pulling my hair out; I found the problem where Eloquent is setting:
protected $primaryKey = 'id';
which is used on the update method and returned by getKeyName().
protected function setKeysForSaveQuery(Builder $query)
{
$query->where($this->getKeyName(), '=', $this->getKeyForSaveQuery());
return $query;
}
I then realised my 'id' on the tale was uppercase and not lower case!
I guess that means my answer is that I need to ensure I am using lowercase 'id' for the primary key or overriding it on the Model
protected $primaryKey = 'ID';
I have a similar problem. My model had:
protected $fillable = ['user_x_cliente_id','internet_cliente_id'];
The status has 0.
$habilita = leilao_habs::updateOrCreate(
[ 'user_x_cliente_id' => $user_x_cliente->id,
'internet_cliente_id' => $int_cli->id],
['status' => 1]
);
dd($habilita);
After execute the updateOrCreate , the status still 0 and No get MassAssignmentException error.
The solution was change the model adding the status to protected $fillable:
protected $fillable = ['user_x_cliente_id','internet_cliente_id','status'];
Now the updateOrCreate works changing the status.