gpt4 book ai didi

mysql - Laravel LastInsertId 与 UUID PK

转载 作者:可可西里 更新时间:2023-11-01 07:03:36 28 4
gpt4 key购买 nike

我正在尝试使用 UUID 作为 Laravel 4 的主键。

没有找到关于这个主题的太多信息,我决定在 MySQL 中使用触发器在插入时将 id 列设置为 UUID() 的值。

根据我的阅读,我需要在

的模型中设置一个 var
public $incrementing = false;

在我的迁移文件中,每个表都有这样的内容:

//set default id to UUID, requires thread_stack in my.cnf to be 196k
function makeTrigger($tableName)
{
DB::unprepared('CREATE TRIGGER '.$tableName.'_trigger_id BEFORE INSERT ON '.$tableName.' FOR EACH ROW SET NEW.id = UUID()');
}

$tableName = 'sites';
Schema::create($tableName, function($table)
{
$table->string('id', 36)->primary();
$table->string('name', 50);
$table->string('development_url', 50);
$table->string('production_url', 50);
$table->boolean('launched')->default(0);
$table->string('test');
$table->timestamps();
$table->softDeletes();
});
makeTrigger($tableName);

虽然我可以插入像这样具有 UUID 的记录,但如果在模型中设置了 $incrementing = false,我将无法返回 ID。

如果我删除那个 var 并且我使用的是 UUID,则返回的 id 是 0。如果我在迁移文件中使用 increments('id'),我会得到返回的真实 id。

我正在为规范中的 ids 构建一个 UUID 的应用程序,所以我想弄清楚这在 Laravel 4 中是否可行。

如果我无法使用

取回该 ID
$user = User::create($userdata);

return $user->id;

那么id将如何用于关系呢? (同样的问题使用 $user->save();)

据我所知,Eloquent 期待返回一个 auto_increment,但似乎应该有办法取回任何 id。

为什么这行不通?

任何对此领域的见解都将不胜感激,因为我似乎找不到关于该主题的任何真实文档。

最佳答案

我通过在模型上使用 creating 事件来解决这个问题,以便在保存模型时添加新的 UUID。您还可以在 packagist 上找到我的解决方案.

class BaseModel extends Eloquent {

/**
* Indicates if the IDs are auto-incrementing.
*
* @var bool
*/
public $incrementing = false;

/**
* The "booting" method of the model.
*
* @return void
*/
protected static function boot()
{
parent::boot();

static::creating(function($model)
{
$model->{$model->getKeyName()} = (string)$model->generateNewId();
});
}

/**
* Get a new version 4 (random) UUID.
*
* @return \Rhumsaa\Uuid\Uuid
*/
public function generateNewId()
{
return \Rhumsaa\Uuid\Uuid::uuid4();
}

}

关于mysql - Laravel LastInsertId 与 UUID PK,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17280616/

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