为模型生成唯一的随机ID

时间:2017-06-14 10:33:31

标签: php laravel-5.4

我对Laravel相当新,所以请放轻松我:)我试图找出为模型生成唯一随机ID的最有效方法。此ID应为6个字符,因此我将使用mt_rand(100000,999999)创建它。我想要做的是模型创建,生成ID,检查它是否真正独特,然后将其保存在模型中。

我已经看过观察者这样做但是在创作活动的背后似乎有点冗长。是否有任何替代方法或方法可以在不创建多个文件的情况下调用观察者?

克里斯。

2 个答案:

答案 0 :(得分:1)

如果你想要真正独特的ID,我会调查UUID,以确保你永远不会得到任何重复。我建议使用这个包:https://github.com/webpatser/laravel-uuid

您可以通过以下方式轻松生成UUID:Uuid::generate(4);这将确保其真正随机。

答案 1 :(得分:0)

Ah right, managed to work this out :)

So rather than using events, I just extended the models boot method as this is another way of hooking into model events -

protected static function boot () {

    // run our parent boot
    parent::boot();

    // hook onto our creating method
    static::creating(function($model) {
        /** @var $model Candidate */
        $model->_generateAccessCode();
    });
}

This then tells the model that when a new one is being created (using the creating event), to generate a new access code.

I've then added the _generateAccessCode() method into the model -

/**
 * Called on Candidate model creation
 * @return void
 */
private function _generateAccessCode () {

    // make sure our value is unique by checking it doesn't exist already
    while(empty($this->access_code) || self::findByAccessCode($this->access_code, ['id'])) {
        $this->access_code = mt_rand(100000, 999999);
    }
}

Which references another method to verify an access code doesn't yet exist -

/**
 * Retrieve a candidate by access code
 * @param int $code 6 digit access code
 * @param array $columns Array of columns
 * @return mixed
 */
public static function findByAccessCode ($code, $columns = []) {

    if(count($columns) < 1) $columns = null;

    // get our candidate by access code
    $candidate = Candidate::where('access_code', '=', $code)->first($columns);

    // return our candidate
    return $candidate;
}