在我的Laravel应用中,当用户提交新订单时,我在表中设置了一个order-id列,以将日期,经过身份验证的用户的用户ID和一个从1开始的计数器连接起来像这样的控制器;
$date = date ('ymd');
$user = Auth::id ();
$count = 1;
$order = new Order;
$order->order-id = $date. $user. $count;
$order->save ();
$count++;
现在我要实现的是用户ID为90的用户第一次下订单(例如,在7月1日),订单ID为180701090001
(日期为180701,用户ID为090)和001作为计数器)&当他在7月3日下一个订单说时,我应该得到一个180703090002
的订单ID。但是,我现在不断得到的是180701090001
。我该如何实现?
答案 0 :(得分:0)
为什么不尝试获取最新保存的订单,然后向该订单ID添加一个加号
2237 Strang Avenue
2932 Ely Avenue
3306 Wilson Ave
3313 Wilson Avenue
3313 Wilson Avenue
3313 Wilson Avenue
46 Nuvern Avenue
答案 1 :(得分:0)
也许您可以从中得到一个想法。
echo '<pre>';
class Order
{
#######################
# It would be better to separate the database incrementing id and the transction id for the order
#######################
public $id;
public $transaciton_id;
/**
* Set the incrementing id when the object is instantiated and also set the transaction id for this order
*/
public function __construct($lastid,$user_id)
{
$this->id=$lastid+1;
$this->set_transaction_id($user_id);
}
/**
* Set the transaction id
*
*/
private function set_transaction_id($user_id)
{
$date = date ('ymd');
$this->transaciton_id=$date.sprintf("%03d",$user_id).sprintf("%03d",$this->id);
}
}
$user_id=90;//user id
//array of orders
$orders=[];
//adding new orders
$orders[]=new Order(count($orders),$user_id);
$orders[]=new Order(count($orders),$user_id);
$orders[]=new Order(count($orders),$user_id);
$orders[]=new Order(count($orders),$user_id);
$orders[]=new Order(count($orders),$user_id);
print_r($orders);
结果:
Array
(
[0] => Order Object
(
[id] => 1
[transaciton_id] => 180702090001
)
[1] => Order Object
(
[id] => 2
[transaciton_id] => 180702090002
)
[2] => Order Object
(
[id] => 3
[transaciton_id] => 180702090003
)
[3] => Order Object
(
[id] => 4
[transaciton_id] => 180702090004
)
[4] => Order Object
(
[id] => 5
[transaciton_id] => 180702090005
)
)
更新:
为了获得模型的最后插入的ID,也许您可以通过这种方式进行。这可能不是最佳答案,但您可以获得相同的结果。
public static function model_last_id($model)
{
$example_model=$model::orderBy('id','desc')->First();
if($example_model!=null)
return $example_model->id;
else
return null;
}