在模型中不工作id getter(我使用uuid类型)

时间:2017-04-29 00:32:08

标签: php laravel eloquent laravel-5.4

我在Model中将主键设为uuid。

使用uuid主键迁移:

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

检查模型:

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",
}

访问模型时,它包含正确的数据。

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

为什么为零?

1 个答案:

答案 0 :(得分:1)

Eloquent有一些默认约定,因此对你的模型,表格,约束等有一些期望...... 幸运的是,你可以改变它们:

From the Laravel documentation

  

主键

     

Eloquent还会假设每个表都有一个主键列   命名id。您可以定义$ primaryKey属性来覆盖它   约定。

     

此外,Eloquent假设主键是递增的   整数值,这意味着默认情况下主键将是   自动转换为int。如果你想使用非递增或   一个非数字主键,您必须设置公共$ incrementing   模型上的属性为false。

关于你的问题:"为什么为零?"

因为Eloquent将"e025b8aa-c71e-42ca-b87c-7ee27695b83a"的字符串显式地转换为int值,结果是int 0 ...