【发布时间】:2020-10-29 07:09:01
【问题描述】:
我在 Laravel 6.x 中设置了一个自定义字符串类型的主键,调用
$node=Node::create() 很好,但是稍后调用$node->save() 更新时,它使用where ‘instanceId’=0 来匹配主键,这会抛出 MySQL 1292 错误的异常。
对于表架构(迁移):
public function up()
{
Schema::create('nodes', function (Blueprint $table) {
$table->string('instanceId')->primary();
$table->string('regionId')->nullable();
$table->string('privateIp')->unique()->nullable();
$table->string('publicIp')->unique()->nullable();
$table->string('dnsRecordId')->unique()->nullable();
$table->unsignedTinyInteger('status')->default(0);
$table->unsignedInteger('userId');
$table->timestamps();
});
}
模型定义:
/**
* The primary key associated with the table.
*
* @var string
*/
protected $primaryKey = 'instanceId';
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = [
'instanceId',
'regionId',
'privateIp',
'publicIp',
'dnsRecordId',
'status',
'userId',
];
/**
* The attributes that should be casted to native types.
*
* @var array
*/
protected $casts = [
'userId' => 'integer',
];
【问题讨论】:
-
laravel.com/docs/8.x/eloquent#primary-keys 确保调整与主键相关的其他属性,如果它不是模型上的自动增量整数