Laravel 4 使用 UUID 作为主键

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17241660/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 08:00:51  来源:igfitidea点击:

Laravel 4 using UUID as primary key

phpmysqllaravelprimary-keyuuid

提问by Jazzy

I am setting up my first Laravel 4 app and the specs call for the id fields to be varchar(36) and be a UUID.

我正在设置我的第一个 Laravel 4 应用程序,规范要求将 id 字段设为 varchar(36) 并设为 UUID。

Using Eloquent, my migrations for a sample table looks like this:

使用 Eloquent,我对示例表的迁移如下所示:

Schema::create('users', function($table)
{
    $table->string('id', 36)->primary;
    $table->string('first_name', 50);
    $table->string('last_name', 50);
    $table->string('email')->unique();
    $table->string('password', 60);
    $table->timestamps();
    $table->softDeletes();
});

When the users table gets created, the id field is not defined as PK, or unique. It gets defined as varchar(36) NOT NULL.

创建用户表时,id 字段未定义为 PK 或唯一。它被定义为 varchar(36) NOT NULL。

Why is this happening when I run the migration?

为什么在我运行迁移时会发生这种情况?



My original question was about using UUIDs, but I have sense solved that by adding this to my Users model in case anyone else sees this post:

我最初的问题是关于使用 UUID,但我感觉通过将它添加到我的用户模型中解决了这个问题,以防其他人看到这篇文章:

protected $hidden = array('password');

protected $fillable = array('id', 'first_name', 'last_name', 'email', 'password');

Here is my route for adding a user (I am using a function to create the UUID):

这是我添加用户的路线(我正在使用一个函数来创建 UUID):

Route::post('signup', function()
{
    $userdata = array(
        'id' => gen_uuid(),
        'first_name' => Input::get('first_name'),
        'last_name' => Input::get('last_name'),
        'email' => Input::get('email'),
        'password' => Hash::make(Input::get('password'))    
    );

    $user = new User($userdata);
    $user->save();

    return View::make('login/login')->with('userdata', $userdata);
}); 

回答by Antonio Carlos Ribeiro

This line

这条线

$table->string('id', 36)->primary;

Must be changed to

必须改为

$table->string('id', 36)->primary();