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

倖福魔咒の 提交于 2019-12-13 07:37:53

问题


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...



来源:https://stackoverflow.com/questions/43690619/not-work-id-getter-in-model-i-use-uuid-type

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