插入数据库中不存在的随机整数不起作用?

Insert a random int that does not exist in Dtabase not working?

mt_rand() 和 random_int() 都只生成一个数字并将其插入到该数字已经存在的数据库中。我想清楚一点,我想插入一个数据库中不存在的随机数。

我从

中获取了这段代码

在我的例子中 laravel 8,代码如下所示

public function generateProductCode() {
    $number = mt_rand(1000000000, 9999999999); 

    // call the same function if the barcode exists in Dtabase already
    if ($this->productCodeExists($number)) {
        return $this->generateProductCode();
    }

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

public function productCodeExists($number) {
    // query the database and return a boolean
    // for instance, it might look like this in Laravel
    return Product::where('product_code', $number)->exists();
}

模型名称是产品,数据库table名称是产品。 'product_code' 是我要执行此查询的列。 在我调用 generateProductCode() 函数的存储函数中,如下所示

public function store(Request $request)
{
    $product = new Product;
    //Generate a Product key
    $product->product_code = $this->generateProductCode();
    $product->save();
 }

它 returns 一直只有一个数字,即 2147483647 。 Photo is here 怎么了?什么是检查存在的完美查询,以便它 returns 另一个不存在于数据库中。

根据php doc

mt_rand: This function does not generate cryptographically secure values, and should not be used for cryptographic purposes

你可以使用random_int

它生成适用于无偏结果至关重要的加密随机整数

 $number = random_int(1000000000, 9999999999); 

您应该创建一个递归函数来检查该号码是否已被使用。

public function store(Request $request)
{
    $product = new Product;
    //Generate a Product key
    $product->product_code = $this->newRandomInt();
    $product->save();
 }

 private function newRandomInt()
    {
        $number = random_int(1000000000, 9999999999); 
        $isUsed =  Product::where('number', $number)->first();
        if ($isUsed) {
            return $this->newRandomInt();
        }
        return $number;
    }