laravel 5.6 id is automatically casted to int

你说的曾经没有我的故事 提交于 2020-05-14 19:28:29

问题


I'm using Laravel 5.6 with the following table structure:

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();
})

When I dump a single record, laravel has converted the id field to an integer:

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 [▶]
}

In my model I have added the following without any luck:

class Traffic extends Model {

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

From what I've found so far this should be the way to cast the id field to type string. So I'm either doing something wrong or this is a bug. Any ideas on how I could solve this?

I know it wold probably be solved if I created an integer field id or rename the current field to something else. But I'm hoping there is a better solution.


回答1:


As ZeroOne mentioned:

have you add this public $incrementing = false;.. need to be disable i think

This worked for me.



来源:https://stackoverflow.com/questions/49411532/laravel-5-6-id-is-automatically-casted-to-int

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!