在Eloquent模型中,UUID主键以uuid形式存储,但返回值为0。

17
我有一个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));
    }

}

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

uuids stored

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

creating new instance and dumping id

它返回为0:

returned result

这里我错过了什么?
1个回答

37

我在文档中搜索后找到了答案: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));
    }
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接