关于订单,有数据库里有两张表,一张是order表(订单表)用于支付(id,userid,订单总金额,收件人姓名,电话,地址,支付状态标识,订单生成时间);另一张是订单详情表,用于用户查看订单里的商品详细信息(id,orderid,商品id,商品价格,数量,图片等信息)
订单生成的流程:购物车里的商品+地址信息(通过地址id获取收货地址信息)+session(user)==>生成订单表,然后购物车清空;生成订单表只在form表单里提交地址id,商品信息从购物车获取(目的是尽量减少用用户提供的信息,提高安全性);从购物车里遍历获取商品信息+orderid==>订单详情表。
public function create_order() { // $addr = $this->show_address(); $comm = $this->get_order_comm(); $N = count($comm['comm_list']); if($N==0) $this->error("购物车里还木有商品哦",U('index/select_all')); //根据地址id查出地址表 $tb_list = M('useraddress'); $where['id'] = I('address_id'); if ( I('address_id') == '' ) { $this->error('请选择收件人地址'); } $addr = $tb_list->where($where)->find(); $data = array(); $user = session('user'); $data['userid'] = $user['id']; // 下单用户 $data['username'] = $addr['name']; //收件人 $data['useraddress'] = $addr['address']; // 收件地址 $data['userphone'] = $addr['tel']; // 电话 $data['total_price'] = $comm['total']; // 总价 $id = M('order')->add($data);//生成订单,反馈订单id // 遍历商品列表 加入订单详情 foreach ($comm['comm_list'] as $value) { $tmp = array(); $tmp['orderid'] = $id; $tmp['commid'] = $value['id']; $tmp['commname'] = $value['name']; $tmp['commimg'] = $value['img']; $tmp['commprice'] = $value['price']; $tmp['commnum'] = $value['num']; M('order_detail')->add($tmp); } $this->success('订单已提交,请尽快支付','show_order_list'); $this->destroy_cart(); }
//提交订单,清除购物车
private function destroy_cart()
{
$user = session('user');
$where = array('userid'=>$user['id']);
$list = M('cart')->where($where)->delete();
}
//获取购物车内的商品总价+商品list
public function get_order_comm()
{
$cart_list = $this->show_comm(); // 购物车
$comm_list = $this->get_com_info($cart_list); // 商品详情
$total = 0;
foreach ($cart_list as $value)
{
$sum = $comm_list[$value['commodity_id']]['price']*$value['commodity_number'];
$total = $total + $sum;
}
$re = array();
$re['total'] = $total;
$re['comm_list'] = $comm_list;
return $re;
}
////结算单 展示购物车商品
private function show_comm()
{
$user_id = session('user');
$array = array();
$array['userid'] = $user_id['id'];
$list = M('cart')->where($array)->select();
$this->assign('result',$list);
$this->get_com_info($list);
return $list;
}
//获取购物车里的商品信息,参数为购物车list
public function get_com_info($cart_list)
{
$result = array();
$tb_com = M('commodity');
foreach ($cart_list as $value)
{
$single = $tb_com->where('id='.$value['commodity_id'])->find();
$single['num'] = $value['commodity_number'];
$result[$value['commodity_id']] = $single;
}
$this->assign('commodity',$result);
return $result;
}