Laravel 4:如何使用迁移创建非主要自动递增列?

chr*_*der 8 php mysql database-design laravel laravel-4

我目前正在开发一个由主服务器和许多客户端组成的Laravel 4项目.客户端创建数据并将其发送到主服务器.为避免冲突,我使用UUID v4作为主键.

但是,一旦在服务器上创建数据,我想分配一个唯一的自动递增整数,以便用户更容易识别数据.例如:而不是说item 5a8e896d-3ab4-48d2-9d39-faeb5227f012一个用户可以谈论item #24567

为了保持我的应用程序可管理我正在使用迁移,我对此表的当前迁移如下所示:

public function up()
{
    Schema::table('items', function($table)
    {
        $table->create();
        $table->string('id')->primary(); //'id' For the purpose of keeping the ORM working, this field stores the UUID.
        $table->integer('number', true); //The human readable item number, the second parameter is true for auto-increment
        $table->text('otherdata');
        $table->timestamps();
    });
}
Run Code Online (Sandbox Code Playgroud)

问题是Laravel在定义自动增量时会自动创建主键,因此迁移最终会失败,因为有两个主键.

[Exception] SQLSTATE[42000]: Syntax error or access violation: 1068 Multiple primary key defined
  (SQL: alter table `items` add primary key items_id_primary(`id`)) (Bindings: array ())
Run Code Online (Sandbox Code Playgroud)

有没有办法使用Laravel 4迁移使用主键和单独的自动递增字段.

chr*_*der 2

我发现了问题,Laravel 似乎正在为每个 auto_increment 字段创建一个主键。当我删除它primary key要求我提供索引的部分时,我要求->unique()进行迁移,但这也不起作用。更改return ' auto_increment primary key';return ' auto_increment unique';解决了我的问题,尽管现在它的核心已被黑客攻击,这当然是不好的做法。

/**
 * Get the SQL for an auto-increment column modifier.
 *
 * @param  Illuminate\Database\Schema\Blueprint  $blueprint
 * @param  Illuminate\Support\Fluent  $column
 * @return string|null
 */
protected function modifyIncrement(Blueprint $blueprint, Fluent $column)
{
    if ($column->type == 'integer' and $column->autoIncrement)
    {
        return ' auto_increment unique'; //return ' auto_increment primary key';
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 我不认为这是更好的解决方案(改变 laravel Db 类的核心功能。)。 (2认同)