在 Laravel 中制作一个带有数字前缀和其他字符串前缀的代码

Make a code with number prefix and other string prefix in Laravel

我必须为交易编号制作一个格式,格式示例是 BKK-202009-00001。将自动执行的数字 00001 increment.I已尝试但未获得预期输出。

编码

public function createBefore($model, $arrayData, $metaData, $id=null) 
{
    //$arrayData["no_draft"] = $this->custom_getdraftid(null);
    $prefix = 'BBK';
  
    if ($arrayData['payment_type']=='CASH') {
        $prefix='BKK';
    } elseif ($arrayData['payment_type']=='GIRO') {
        $prefix='BGK';
    }
    ff($prefix);
    $no_transaction = \DB::table('acc_tra_cash_bank_expenses_header')
    ->selectRaw(" '$prefix' || '-' ||to_char(CURRENT_DATE, 'YYYYMM')||'-'||RIGHT('0000'||(
                            RIGHT( (SELECT no_transaction FROM acc_tra_cash_bank_expenses_header WHERE no_transaction LIKE '$prefix'||to_char(CURRENT_DATE, 'YYYYMM')||'%'
                                        ORDER BY id DESC LIMIT 1),5)::INTEGER+1)::TEXT,5) AS no_transaction")->first();
    ff($no_transaction->no_transaction);
    if (!$no_transaction) {
        $bulantanggal = date('Ym');
        $no_transaction->no_transaction = "$prefix-$bulantanggal-00001";
    }
    
    $newModel = $model;
    $newArrayData  = array_merge($arrayData, [
       'no_draft'=> $this->custom_getdraftid(null),
        'no_transaction' => $no_transaction->no_transaction
    ]);
    return [
        "model"  => $newModel,
        "data"   => $newArrayData,
    ];
}

如果我没理解错的话,您需要像 BKK-202009-00001 这样带有递增数字的格式。一个解决方案就像

$string = 'BKK-202009-00001'; //the last entry from the database
$number = last(explode("-",$string)); //explode the string to get the number part, last is a laravel helper
$new = str_pad(intval($number) + 1, 5, 0, STR_PAD_LEFT); //increment the number by 1 and pad with 0 in left.

$no_transaction->no_transaction = $prefix.'-'.$bulantanggal.'-'.$new; //concat string and number to generate the desired output