【问题标题】:Laravel uses wrong primary key updating mysqlLaravel 使用错误的主键更新 mysql
【发布时间】: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',
];

【问题讨论】:

标签: mysql laravel


【解决方案1】:

看起来您在调用 $node->save() 之前没有设置 instanceId 的值。 所以它看起来像 $node->instanceId 为空,因为 instanceId 是主键,它不能为空。 为防止此类问题,您需要在保存之前设置 instanceId 的值,否则您可以在 createSchema 中设置 instanceId 的默认随机值。

$node->instanceId = str_random(20);

谢谢

【讨论】:

  • 它不是Null,它是在早期create()中设置的,我也在MySQL内部仔细检查过。另外,如果为null,调用所有这些的函数都会提前返回,这是有逻辑的。
  • 能否请您尝试在架构中设置 instanceId 的默认值?
【解决方案2】:

感谢 lagbox,这确实是一个 RTFM 问题。
当使用字符串时,主键 $incrementing=false$keyType=‘string’ 是必需的,否则 Laravel 将假定主键是自增整数。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-01-21
    • 1970-01-01
    • 1970-01-01
    • 2015-06-21
    • 1970-01-01
    • 2021-07-12
    • 2015-05-17
    相关资源
    最近更新 更多