Laravel 5.6将ID自动转换为整数类型。

5
我将使用Laravel 5.6,并有以下表结构:
public function up() {
        Schema::create( 'traffic', function ( Blueprint $table ) {
            $table->string( 'id' );
            $table->unsignedInteger( 'category_id' );
            $table->unsignedInteger( 'magnitude_id' );
            $table->unsignedInteger( 'start_id' )->nullable();
            $table->unsignedInteger( 'destination_id' )->nullable();
            $table->unsignedInteger('locale_id');
            $table->integer( 'length' )->comment( 'in metres' );
            $table->integer( 'delay' )->comment( 'in seconds' );
            $table->decimal( 'position_lat', 10, 8 );
            $table->decimal( 'position_lon', 10, 8 );
            $table->timestamps();
})

当我转储单个记录时,Laravel已将id字段转换为整数:

Traffic {#351 ▼
  #casts: array:1 [▶]
  #connection: "mysql"
  #table: null
  #primaryKey: "id"
  #keyType: "int"
  +incrementing: false
  #with: []
  #withCount: []
  #perPage: 15
  +exists: true
  +wasRecentlyCreated: false
  #attributes: array:13 [▼
    "id" => 3
    "category_id" => 6
    "magnitude_id" => 3
    "start_id" => 1898
    "destination_id" => 1898
    "locale_id" => 3
    "length" => 3650
    "delay" => 3061
    "position_lat" => "5.27669000"
    "position_lon" => "51.85458000"
    "created_at" => "2018-03-21 15:55:13"
    "updated_at" => "2018-03-21 15:55:13"
    "name" => "nl"
  ]
  #original: array:13 [▶]
  #changes: []
  #dates: []
  #dateFormat: null
  #appends: []
  #dispatchesEvents: []
  #observables: []
  #relations: []
  #touches: []
  +timestamps: true
  #hidden: []
  #visible: []
  #fillable: array:10 [▶]
  #guarded: array:1 [▶]
}

在我的模型中,我已经添加了以下内容,但没有任何效果:
class Traffic extends Model {

    protected $casts = [
        'id' => 'string'
    ];

根据我目前的了解,将 id 字段转换为字符串类型可能是这样的。所以要么我做错了什么,要么这是一个错误。你有任何解决方法吗?

我知道如果我创建一个整数字段 id 或将当前字段重命名为其他名称,问题可能会得到解决。但我希望能够找到更好的解决方案。


3
你是否添加了这个public $incrementing = false;?我认为需要禁用它。 - ZeroOne
或者您可以设置protected $keyType ='string';。默认值为 int - DevK
实际上,protected $casts = ['id' => 'string'] 完全正常。你没有看到它是因为你使用了 dd($model) 并查看了 attributes 属性,这只是在访问器被应用之前数据库记录的副本(包括 $casts)。 - DevK
$incrementing = false 对我有效,而 $keyType = 'string' 则无效。 - Rav
1个回答

6

ZeroOne所述:

你是否添加了这个public $incrementing = false;..需要禁用它,我想

这对我起作用了。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接