使用UUID PK的Laravel LastInsertId

时间:2013-06-24 16:41:40

标签: mysql laravel laravel-4 uuid eloquent

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

没有找到关于这个主题的更多信息我决定在MySQL中使用一个触发器来设置id列,其值为UUID()on insert。

根据我的阅读,我需要在

模型中设置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.如果我在迁移文件中使用增量(' id'),则会返回真实ID。

我正在为规范中的ID建立一个UUID的应用程序,所以我想知道这是否可以在Laravel 4中使用。

如果我无法使用

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

return $user->id;

然后如何将id用于关系? (使用$ user-> save();)

的相同问题

根据我的理解,Eloquent期待auto_increment回归,但似乎应该有办法让任何id回来。

为什么要赢得这项工作?

对此领域的任何见解都将受到赞赏,因为我似乎无法找到关于此主题的任何真实文档。

1 个答案:

答案 0 :(得分:7)

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

}