Eloquent模型中的UUID主键存储为uuid,但返回0

Chr*_*itz 11 uuid laravel eloquent

我有一个mysql表,其中我使用UUID作为主键.这是创建迁移:

Schema::create('people', function (Blueprint $table) {
    $table->uuid('id');
    $table->primary('id');
    ...
    $table->timestamps();
}
Run Code Online (Sandbox Code Playgroud)

这会生成以下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;
Run Code Online (Sandbox Code Playgroud)

在我的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));
    }

}
Run Code Online (Sandbox Code Playgroud)

当我创建一个新的模型实例时,它将它存储在数据库中:

uuids存储

但是当我尝试访问新实例的id时:

创建新实例并转储id

它返回0:

返回结果

我在这里错过了什么?

Chr*_*itz 15

没关系,我在搜索了文档后找到了答案:https://laravel.com/docs/5.2/eloquent#eloquent-model-conventions

在"主键"部分下面有一点点模糊:

此外,Eloquent假定主键是递增的整数值.如果要使用非递增主键,则必须将模型上的$ incrementing属性设置为false.

如果您要使用UUID,则必须将此属性设置为false.一旦我在我的模型的顶部做到这一点它工作.

由于我的所有模型都将使用UUID,因此我将UUID逻辑提取到父类.这是它的样子:

class UuidModel extends Model
{

    public $incrementing = false;

    /**
     * Sets the UUID value for the primary key field.
     */
    protected function setUUID()
    {
        $this->id = preg_replace('/\./', '', uniqid('bpm', true));
    }
}
Run Code Online (Sandbox Code Playgroud)