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

How to generate unique random value for each user in laravel and add it to database(如何在laravel中为每个用户生成唯一的随机值并将其添加到数据库中)
本文介绍了如何在laravel中为每个用户生成唯一的随机值并将其添加到数据库中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

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

I am developing a event organization website. Here when the user registers for an event he will be given a unique random number(10 digit), which we use to generate a barcode and mail it to him. Now,

  1. 我想为每个注册的活动设置唯一的编号.
  2. 也是随机的

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

One solution is to grab all the random numbers in an array and generate a random number using Php rand(1000000000, 9999999999) and loop through and check all the values. Grab the first value that doesn't equal to any of the values in the array and add it to the database.

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

But I am thinking that there might be a better solution to this. Any suggestion?

推荐答案

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

Your logic isn't technically faulty. However, if your application attracts lots of users, fetching all of the random numbers may well become unnecessarily expensive, in terms of resources and computation time.

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

I would suggest another approach, where you generate a random number and then check it against the database.

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();
}

这篇关于如何在laravel中为每个用户生成唯一的随机值并将其添加到数据库中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

本站部分内容来源互联网,如果有图片或者内容侵犯了您的权益,请联系我们,我们会在确认后第一时间进行删除!

相关文档推荐

DeepL的翻译效果还是很强大的,如果我们要用php实现DeepL翻译调用,该怎么办呢?以下是代码示例,希望能够帮到需要的朋友。 在这里需要注意,这个DeepL的账户和api申请比较难,不支持中国大陆申请,需要拥有香港或者海外信用卡才行,没账号的话,目前某宝可以
PHP通过phpspreadsheet导入Excel日期,导入系统后,全部变为了4开头的几位数字,这是为什么呢?原因很简单,将Excel的时间设置问文本,我们就能看到该日期本来的数值,上图对应的数值为: 要怎么解决呢?进行数据转换就行,这里可以封装方法,或者用第三方的
mediatemple - can#39;t send email using codeigniter(mediatemple - 无法使用 codeigniter 发送电子邮件)
Laravel Gmail Configuration Error(Laravel Gmail 配置错误)
Problem with using PHPMailer for SMTP(将 PHPMailer 用于 SMTP 的问题)
Issue on how to setup SMTP using PHPMailer in GoDaddy server(关于如何在 GoDaddy 服务器中使用 PHPMailer 设置 SMTP 的问题)