Laravel使用UUID作为主键,如何获取最新插入记录的ID?

6

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

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

根据我所读的,我需要在模型中设置一个变量:

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。
如果我删除该变量并使用UUID,则返回的ID为0。如果在迁移文件中使用increments('id'),则返回真正的ID。
我正在构建一个使用规范中的UUID作为ID的应用程序,因此我正在尝试确定在Laravel 4中是否可能实现此目标。
如果我无法使用...获取该ID
$user = User::create($userdata);

return $user->id;

那么如何使用 id 来建立关系呢?(在使用 $user->save(); 时遇到同样的问题)

据我所知,Eloquent 期望返回一个自增的 id,但似乎应该有一种方法可以获得任何 id。

为什么这不起作用?

如果您对此领域有任何见解,将不胜感激,因为我似乎找不到任何关于此主题的真正文档。

1个回答

8

我通过在模型上使用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();
    }

}

是的,我也有同感,这很遗憾,因为触发器看起来非常不错。 - malhal

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