I'm making a system and within this system I have a piece of code which checks for the latest "Order" using the created_at field and it checks the latest "Order_nr" and when a new one is created the number of order_nr
goes +1. Here is the code I'm talking about
$order = new Order;
$order->user_id = Auth()->id();
$latestOrder = Order::orderBy('created_at', 'DESC')->first();
$order->order_nr = '#'.str_pad($latestOrder->id + 1, 8, "0", STR_PAD_LEFT);
$order->sub_total = $subtotal;
$order->vat = $vat;
$order->price_sum = $priceSum;
$order->save();
this makes every order number unique. When I seed my database the timestamps are all the same. Now when I try to save the order by executing the code above I get the following error:
SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry '#00000002' for key 'orders_order_nr_unique' (SQL: insert into
orders
(user_id
,order_nr
,sub_total
,vat
,price_sum
,updated_at
,created_at
) values (1, #00000002, 18.12, 3.8052, 21.9252, 2018-03-28 07:30:51, 2018-03-28 07:30:51))
When I change the latest order's time to a second later the code works just fine. How can I solve this? What is the best way to execute this?
from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/2pKD7Uc
via IFTTT
Aucun commentaire:
Enregistrer un commentaire