如何使用现有随机数据设置序列数据?

时间:2017-07-07 03:39:53

标签: php laravel laravel-5

我有一个表实体,将其命名为uniqueId,其中条目随机生成。例如

$customer->uniqueId = $request->Input(['uniqueId']) ?: mt_rand(1000, 9999); 

表示如果存在uniqueId,它将存储现有的,否则将设置为随机数。现在,而不是设置随机数,我想将其设置为顺序。意思是1,2,3这样的...因为我不能删除现有的uniqueId,它已经创建了如何按现有顺序创建新条目?

1 个答案:

答案 0 :(得分:0)

如果你只是将列设置为自动增量,你将自动实现这一点,你甚至不需要调用它。

在laravel中,您可以通过

在迁移中实现此目的

$table->increments('uniqueId');

您可以通过

实现这一目标

假设您有一个客户模型

 // find the last entry in you table

$oldCustomer = Customer::orderBy('uniqueId','DESC')->first();

$customer->uniqueId = ++($olderCustomer->uniqueId);

我希望这会有所帮助

**编辑**

  $customers = Customer::all();

  $index = 1;
  @foreach($customers as $customer)
  {
      $customer->uniqueID = $index++;
      $customer->update(); 
  }