我有一个带有发票的应用程序,我将发票 ID 设置为自动递增。
我的客户希望 ID 包含年份,并在一年过去后从 1 重新开始。例如 ids 可能看起来像这样。
2023-344 2023-345 2023-346 ETC... 直到我们到达 2024 年,在这种情况下,下一个 id 将是 2024年1月
我从未尝试过自定义 mysql 中的 id 列,并且我不确定这样的更改会如何影响索引速度。我想知道处理这个问题的最佳方法是什么。
我的应用程序在 Laravel 中,我的数据库在 mysql 中
您可以添加单独的列
invoice_id
。并且可以在您的模型中编写新方法:
Schema::create('invoices', function (Blueprint $table) {
$table->string('invoice_id');
$table->index('invoice_id');
});
public static function createNewInvoice() {
$currentYear = now()->year;
$lastInvoice = Invoice::where('year', $currentYear)->orderBy('number', 'desc')->first();
$number = $lastInvoice ? $lastInvoice->number + 1 : 1;
$invoice = new Invoice();
$invoice->year = $currentYear;
$invoice->number = $number;
$invoice->save();
return $invoice;
}
您可以根据需要修改方法。