2013-03-13 96 views
8

我目前正在致力于一个由主服务器和许多客户端组成的Laravel 4项目。客户端创建数据并将其发送到主服务器。为了避免冲突,我使用UUID v4作为主键。Laravel 4:如何使用迁移创建非主自动递增列?

但是,一旦在服务器上创建了数据,我想分配一个唯一的自动递增整数,以便用户更容易识别数据。例如:不要谈论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(); 
    }); 
} 

的问题是,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迁移有一个主键和一个单独的自动递增字段的表。

回答

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'; 
    } 
} 
+2

我不这么认为,这是更好的解决方案(改变laravel Db类的核心功能)。 – 2013-03-25 09:15:49

+1

如果您已经阅读我的评论,您会理解您的解决方案并未回答我的问题。这就是为什么我低估了它。我知道我的解决方案不是最佳实践,但是你的解决方案并不能解决我的问题。 – christiaanderidder 2013-03-25 13:52:15

+0

所以你需要两个单独的列,一个是自动递增的主键和另一个uuid键。我对吗? – 2013-03-25 13:58:55

-2

是的,你可以做到这一点在你的项目类的模型申报

class Items extends Eloquent { 
    /** 
* Indicates if the IDs are auto-incrementing. 
* 
* @var bool 
*/ 
public $incrementing = false; 

} 

现在你的主键是没有更多的自动递增领域。

+0

在我的问题中我说我需要一个递增(非主键)和一个主键,但是当我将列标记为自动递增时,Laravel似乎正在创建第二个主键。如何禁用模型中的自动增量(我在谈论迁移)会改变这种行为? – christiaanderidder 2013-03-24 09:53:11

+5

这与他所问的恰恰相反。 – 2014-03-03 10:29:00

-1

我认为不修改核心文件是无法完成的,因为创建auto_ increment会自动将其作为主键。

更好的是,如果你能在Larvel框架开发中报告它为错误。球队。

here 谢谢:)

0

关键是要增加它的架构之外::创建这样

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;'); 

然后重新迁移,关键在TABLE表名与名ID,然后创建你可以像任何其他键一样访问它。