在生成订单前需要验证是否登录、如果没有登录跳转到登录页面
//验证是否登录
if (!session('?user')){
//登陆成功后返回的地址
session('back_url','getOrderInfo');
return redirect('login');
}
在登录是检测缓存中是否有要返回的路径、如果有则返回
//记录用户信息
session('user',$res);
$back_url = session('back_url') ? : 'index';
return redirect($back_url);
创建订单
/**
* 创建订单
* @param $address_id
* @return array
* @throws Exception
* @throws \think\db\exception\DataNotFoundException
* @throws \think\db\exception\DbException
* @throws \think\db\exception\ModelNotFoundException
*/
public static function createOrder($address_id){
//判断是否有库存
//查询购买商品信息
$goods_info = \app\home\model\Cart::with(['Goods','specGoods'])->where('user_id',session('user.id'))->where('is_selected',1)->select()->toArray();
foreach ($goods_info as $val){
if ($val['number'] > $val['store_count'] - $val['store_frozen']){
throw new Exception('库存不足,请稍后购买');
}
}
//判断是否登录
if (!session('?user')){
throw new Exception('请登录');
}
//生成订单号
$order_number = date('YmdHis').rand(1000,9999);
//查询用户选择的地址
$address_info = Address::find($address_id)->toArray();
//计算商品总价格
$total_price = 0;
foreach($goods_info as $val){
$total_price += $val['price'] * $val['number'];
}
//开启事物
Db::startTrans();
try {
//添加订单基本信息
$data = [
'order_sn' => $order_number,
'user_id' => session('user.id'),
'consignee' => $address_info['consignee'],
'address' => $address_info['area'].$address_info['address'],
'phone' => $address_info['phone'],
'goods_price' => $total_price,
'order_amount' => $total_price,
'shipping' => $total_price,
'create_time' => time()
];
$resulf = \app\home\model\Order::create($data);
if (!$resulf){
throw new Exception('订单信息添加失败');
}
//订单商品信息
$add_order_goods = [];
foreach($goods_info as $val){
$add_order_goods[] = [
'order_id' => $resulf['id'],
'goods_id' => $val['id'],
'spec_goods_id' => $val['spec_goods_id'],
'number' => $val['number'],
'goods_name' => $val['goods_name'],
'goods_logo' => $val['goods_logo'],
'goods_price' => $val['price'],
'spec_value_names' => $val['value_names'],
'create_time' => time()
];
$store_update[] = [
'id' => $val['id'],
'store_count' => $val['store_count'] - $val['number'], //库存 - 购买数量
'store_frozen' => $val['store_frozen'] + $val['number'], //冻结库存 + 购买数量
'update_time' => time()
];
}
//商品订单信息入库
$goods_resulf = (new OrderGoods())->saveAll($add_order_goods);
if (!$goods_resulf){
throw new Exception('下单失败');
}
//修改商品的库存和冻结库存
$store_resulf = (new SpecGoods())->saveAll($store_update);
if (!$store_resulf){
throw new Exception('下单失败');
}
//清空购买的商品信息(购物车)
$delcartgoods = \app\home\model\Cart::destroy(array_column($goods_info,'id'));
if (!$delcartgoods){
throw new Exception('下单失败');
}
//提交事务
Db::commit();
return [
'order_number' => $order_number,
'price' => $total_price
];
}catch (Exception $exception){
//回滚事务
Db::rollback();
throw new Exception($exception->getMessage());
}
}
|