PHP 生成唯一编号

发布于:2023-09-14 ⋅ 阅读:(99) ⋅ 点赞:(0)
 /**
  //region 事件代码块
    /**
     * @desc (插入前操作)
     * @param QbModel $model 模型
     * @return bool
     */
    public static function onBeforeInsert(QbModel $model): bool
    {
        //插入前-开始
        \app\library\Utils::generalModelSn($model, 'VOU', 'user_name');//插入前-结束
        return true;
    }

     * 生成
     * @param QbModel $model
     * @param string|Closure $prefix 前缀
     * @param string $field
     * @return void
     */
    public static function generalModelSn(QbModel $model, $prefix = '', string $field = 'sn')
    {
        if (!$model->getAttr($field)) {
            do {
                if ($prefix instanceof Closure) {
                    $sn = $prefix();
                } else {
                    $sn = generate_no($prefix);//调用生成
                }
            } while ($model->queryWithTrashed()->where($field, $sn)->value('id'));//判断是否存在,有循环生成
            $model->set($field, $sn);
        }
    }
    
/**
 * 生成编码
  *@param string|Closure $field('C') 前缀
 * @return string
 */
function generate_no($prefix = '')
{
    return $prefix . date('ymd') . str_pad(mt_rand(1, 999999), 6, '0', STR_PAD_LEFT);
}