我目前正在做一个Laravel 4项目,由一个主服务器和许多客户端组成。客户端创建数据并将其发送到主服务器。为了避免冲突,我使用UUID v4作为主键。
但是,一旦在服务器上创建了数据,我想分配一个唯一的自动递增的整数,以便用户更容易识别数据。例如:用户可以谈论item #24567
而不是item 5a8e896d-3ab4-48d2-9d39-faeb5227f012
为了保持我的应用程序可管理,我正在使用迁移,我当前的迁移表看起来像这样:
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();
});
}
问题是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 ())
是否有办法使用Laravel 4迁移有一个主键和一个单独的自动递增字段的表
我发现了问题,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';
}
}
技巧是将它添加到Schema::create之外,像这样
Schema::create('payments', function(Blueprint $table)
{
$table->string('primaryKey', 30);
$table->primary('primaryKey');
//...
});
DB::statement('ALTER Table tableName add id INTEGER NOT NULL UNIQUE AUTO_INCREMENT;');
我认为不修改核心文件是不可能做到的,因为创建auto_ increment会自动使它成为主键。
如果你能把它作为bug报告给Larvel框架开发团队就更好了。
这里的谢谢:)
可以在Items类的Model声明中设置
class Items extends Eloquent {
/**
* Indicates if the IDs are auto-incrementing.
*
* @var bool
*/
public $incrementing = false;
}
现在你的主键不再是自动递增的字段