Not work id getter in model (i use uuid type)

2019-09-08 10:31发布

问题:

I make the primary key as uuid in Model.

Migration with uuid primary key:

Schema::create('brands', function (Blueprint $table) {
    $table->uuid('id')->unique()->primary();
    $table->string('title');
    $table->timestampsTz();
});

Checking model:

Psy Shell

>>> $x = App\Models\Brand::find('e025b8aa-c71e-42ca-b87c-7ee27695b83a');
=> App\Models\Brand {#720
  id: "e025b8aa-c71e-42ca-b87c-7ee27695b83a",
  title: "Batman",
  created_at: "2017-04-28 23:51:41+10",
  updated_at: "2017-04-28 23:51:41+10",
}

When accessing the model, it contains the correct data.

>>> $x->title
=> "Batman"
>>> $x->id
=> 0

Why zero?

回答1:

Eloquent has some default conventions and thus has some expectations on your model, table, constraints etc... Luckily, you can change them:

From the Laravel documentation:

Primary Keys

Eloquent will also assume that each table has a primary key column named id. You may define a $primaryKey property to override this convention.

In addition, Eloquent assumes that the primary key is an incrementing integer value, which means that by default the primary key will be cast to an int automatically. If you wish to use a non-incrementing or a non-numeric primary key you must set the public $incrementing property on your model to false.

Regarding your question: "Why zero?"

Because Eloquent casts the string of "e025b8aa-c71e-42ca-b87c-7ee27695b83a" explicitly to an int value and that result is int 0...