Laravel 5.2 中的自动发票编号生成
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/38544748/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Auto Invoice Number Generation in Laravel 5.2
提问by edmond
I am building an invoice application using laravel 5.2
我正在使用 laravel 5.2 构建发票应用程序
I want to create automatic invoice numbers incrementing. Meaning,
我想创建自动递增的发票编号。意义,
If i open create invoice page, i should automatically get #0001 so when i save the invoice, under my invoice_number field it will be 0001 then when i am creating another invoice, the controller will check for the last invoice_number in the database and automatically give me #0002.
如果我打开创建发票页面,我应该自动获得#0001 所以当我保存发票时,在我的 invoice_number 字段下它将是 0001 然后当我创建另一个发票时,控制器将检查数据库中的最后一个 invoice_number 并自动给出我#0002。
Any idea on how to do that or something similar??
关于如何做到这一点或类似的任何想法?
Thanks
谢谢
回答by Daniel
Get the last record from the db in descending order.
按降序从数据库中获取最后一条记录。
$invoice = new Invoice();
$lastInvoiceID = $invoice->orderBy('id', DESC)->pluck('id')->first();
$newInvoiceID = $lastInvoiceID + 1;
This will return the last ID. Then add 1 to it, and display it on the front end {{ $newInvoiceID }}
.
这将返回最后一个 ID。然后加1,显示在前端{{ $newInvoiceID }}
。
Possible issue: What if two users are creating invoices simultaneously? Once they save, the numbers will be different if invoice number is a unique identifier.
可能的问题:如果两个用户同时创建发票怎么办?保存后,如果发票编号是唯一标识符,则编号将不同。
One option is to create invoices per user.
一种选择是为每个用户创建发票。
$invoice = new Invoice();
$lastInvoiceID = $invoice->where('user_id', '=', Auth::user()->id)->orderBy('invoice_id', DESC)->pluck('invoice_id')->first();
$newInvoiceID = $lastInvoiceID + 1;
回答by T. Ato
Auto-increment the invoice_number field in your MySQL table (or just use the 'ID' as your invoice_number:
自动增加 MySQL 表中的 invoice_number 字段(或仅使用“ID”作为您的 invoice_number:
CREATE TABLE invoices (
ID int NOT NULL AUTO_INCREMENT,
invoice_number NOT NULL AUTO_INCREMENT
)
Every time you add an invoice to the table, MySQL automatically assigns it the next number. So if the last invoice in the table is 3, the next one you insert will be assigned 4.
每次向表中添加发票时,MySQL 都会自动为其分配下一个编号。因此,如果表中的最后一张发票是 3,则您插入的下一张发票将被分配 4。
If you want to display the numbers like #0003 and #0004, just query the database for the invoice_number and format the number in PHP.
如果要显示#0003 和#0004 之类的数字,只需在数据库中查询invoice_number 并在PHP 中格式化数字。