如何为laravel中的每个用户生成唯一的随机值并将其添加到数据库

Nas*_*jim 7 php mysql random laravel eloquent

我正在开发一个活动组织网站.在这里,当用户注册一个事件时,他将获得一个唯一的随机数(10位数),我们用它来生成条形码并将其邮寄给他.现在,

  1. 我想让每个注册事件的编号都是唯一的.
  2. 而且随机

一种解决方案是获取数组中的所有随机数并使用Php rand(1000000000,9999999999)生成随机数并循环并检查所有值.获取不等于数组中任何值的第一个值,并将其添加到数据库中.

但我认为可能有更好的解决方案.有什么建议吗?

Abh*_*war 22

你可以使用php的uniqid()函数根据microtime生成一个唯一的ID(当前时间,以微秒为单位)

例:

<?php
echo uniqid();
?>
Run Code Online (Sandbox Code Playgroud)

输出:

56c3096338cdb
Run Code Online (Sandbox Code Playgroud)

  • *警告* 该函数不保证返回值的唯一性。由于大多数系统通过NTP等方式调整系统时钟,系统时间不断变化。因此,该函数可能不会返回进程/线程的唯一 ID。使用 more_entropy 来增加唯一性的可能性。 (3认同)

Joe*_*inz 9

你的逻辑在技术上并不是错误的.但是,如果您的应用程序吸引了大量用户,那么就资源和计算时间而言,获取所有随机数可能会变得不必要地昂贵.

我建议另一种方法,你生成一个随机数,然后对数据库进行检查.

function generateBarcodeNumber() {
    $number = mt_rand(1000000000, 9999999999); // better than rand()

    // call the same function if the barcode exists already
    if (barcodeNumberExists($number)) {
        return generateBarcodeNumber();
    }

    // otherwise, it's valid and can be used
    return $number;
}

function barcodeNumberExists($number) {
    // query the database and return a boolean
    // for instance, it might look like this in Laravel
    return User::whereBarcodeNumber($number)->exists();
}
Run Code Online (Sandbox Code Playgroud)


Had*_*ote 5

这很好:

do {
   $refrence_id = mt_rand( 1000000000, 9999999999 );
} while ( DB::table( 'transations' )->where( 'RefrenceID', $refrence_id )->exists() );
Run Code Online (Sandbox Code Playgroud)