Laravel 9使用非id主键时数据显示异常的原因及解决办法
问题解决方法
你的核心问题出在模型的$incrementing属性设置错误:你赋值的是字符串'false',而非布尔值false。PHP会将非空字符串视为true,导致Eloquent仍然把主键当作自增整数处理,进而对字符串/日期类型的主键做错误的类型转换——字符串转整数会变成0,日期字符串转整数会提取年份部分。
修正步骤
1. 修正$incrementing属性
将模型中的:
public $incrementing = 'false';
改为:
public $incrementing = false;
2. 明确指定主键类型
因为你的主键是字符串类型,需要补充设置$keyType属性(Laravel默认主键类型为int):
protected $keyType = 'string';
修正后的完整模型代码
<?php namespace App\Models; use Illuminate\Database\Eloquent\Factories\HasFactory; use Illuminate\Database\Eloquent\Model; class NonDrivingReasons extends Model { use HasFactory; protected $fillable = ['reason_for_not_driving']; protected $primaryKey = 'reason_for_not_driving'; public $incrementing = false; protected $keyType = 'string'; /** * Set the keys for a save update query. * * @param \Illuminate\Database\Eloquent\Builder $query * @return \Illuminate\Database\Eloquent\Builder */ protected function setKeysForSaveQuery($query) { $keys = $this->getKeyName(); if(!is_array($keys)){ return parent::setKeysForSaveQuery($query); } foreach($keys as $keyName){ $query->where($keyName, '=', $this->getKeyForSaveQuery($keyName)); } return $query; } /** * Get the primary key value for a save query. * * @param mixed $keyName * @return mixed */ protected function getKeyForSaveQuery($keyName = null) { if(is_null($keyName)){ $keyName = $this->getKeyName(); } if (isset($this->original[$keyName])) { return $this->original[$keyName]; } return $this->getAttribute($keyName); } }
验证其他模型
因为你有7张表都使用非自增主键,需要检查所有模型是否存在同样的$incrementing字符串赋值问题,统一修正为布尔值false,并根据主键类型设置对应的$keyType(比如日期类型主键设置protected $keyType = 'date';)。
完成以上修改后,Eloquent会正确识别主键类型,既可以正常显示数据,也能通过主键进行查询操作。
内容的提问来源于stack exchange,提问作者Henry
相关产品推荐
相关产品推荐

