我有一个 mysql 表,其中使用 UUID 作为主键。这是创建迁移:
Schema::create('people', function (Blueprint $table) {
$table->uuid('id');
$table->primary('id');
...
$table->timestamps();
}
它生成以下 MySQL 架构:
CREATE TABLE `people` (
`id` char(36) COLLATE utf8_unicode_ci NOT NULL,
...
`created_at` timestamp NULL DEFAULT NULL,
`updated_at` timestamp NULL DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
在我的 Eloquent 模型中,我有一个创建实例的方法,该实例调用一个生成 UUID 的方法:
class Person extends Model
{
protected $fillable = [
...
];
public function make(array $personData){
$person = new Person;
$person->setUUID();
collect($personData)->each(function ($value, $columnName) use($person){
if(in_array($columnName, $this->fillable)){
$person->{$columnName} = $value;
}
});
$person->save();
return $person;
}
protected function setUUID(){
$this->id = preg_replace('/\./', '', uniqid('bpm', true));
}
}
当我创建一个新的模型实例时,它将它很好地存储在数据库中:
但是当我尝试访问新实例的 id 时:
它返回 0:
我在这里缺少什么?