gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 09:45:38 25 4
gpt4 key购买 nike

我有一个 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

我在这里缺少什么?

最佳答案

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

在“主键”部分下有一个小简介:

In addition, Eloquent assumes that the primary key is an incrementing integer value. If you wish to use a non-incrementing primary key, you must set the $incrementing property on your model to 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));
}
}

关于laravel - Eloquent 模型中的 UUID 主键存储为 uuid 但返回为 0,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35805474/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com