購物車流程
1.創(chuàng)建購物車頁面仿吞,模型,控制器蛹尝,數(shù)據(jù)庫
數(shù)據(jù)表結(jié)構(gòu)如下
CREATE TABLE
cart
(
id
int(11) NOT NULL AUTO_INCREMENT,
goods_id
int(11) NOT NULL,
goods_num
int(11) NOT NULL,
user_id
int(11) NOT NULL,
status
tinyint(1) NOT NULL,
create_time
int(10) NOT NULL,
PRIMARY KEY (id
)
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8;
2.代碼流程
首先獲取頁面?zhèn)鬏斶^來的數(shù)據(jù)
$data = Yii::$app->request->post();
然后判斷用戶是否登錄
if (Yii::$app->user->isGuest)
如果未登錄則將購物車數(shù)據(jù)保存到cookie當中
//調(diào)用此方法將購物數(shù)據(jù)寫入到cookie(在頁面顯示之前沒有真實的寫入)
$this->cartToCookie($data);
//從cookie中獲取數(shù)據(jù)在頁面顯示(剛剛提交的數(shù)據(jù)并不能獲取到)
$cookieCart = Yii::$app->request->cookies->getValue('frontend_cookie');
//1 獲取cookie中的所有購物車數(shù)據(jù)
$carts = unserialize($cookieCart);
//3 將接收數(shù)據(jù)和cookie中讀取的數(shù)據(jù)合并
if (isset($carts[$data['goods_id']])) {
$carts[$data['goods_id']] += $data['num'];
}else{
$carts[$data['goods_id']] = $data['num'];
}
//2 獲取goods_id在購物車中的所有的商品數(shù)據(jù)
$goodsIdArr = array_keys($carts);
$goods = Goods::findAll($goodsIdArr);
如果用戶已經(jīng)登錄擅憔,則將購物車數(shù)據(jù)寫入進數(shù)據(jù)庫
//1 查詢出購物車中當前用戶待支付的購物車數(shù)據(jù)
$cartGoods = Cart::find()
->where(['goods_id' => $data['goods_id'], 'user_id'=>Yii::$app->user->identity->id, 'status'=>2])
->one();
//2 如果數(shù)據(jù)庫中的待支付數(shù)據(jù)為空直接寫入當前數(shù)據(jù)
if (empty($cartGoods)) {
$cartModel = new Cart();
$cartModel->goods_id = $data['goods_id'];
$cartModel->goods_num = $data['num'];
$cartModel->user_id = Yii::$app->user->identity->id;
$cartModel->status = 2;
$cartModel->create_time = time();
if ($cartModel->save() === false) {
echo '加入購物車失敗';
exit;
}
}else{
//3 如果不為空則將新添加的數(shù)據(jù)更新到當前商品
$cartGoods->goods_num += $data['num'];
if ($cartGoods->save() === false) {
echo '加入購物車失敗';
exit;
}
}
//4 查詢出用戶所有待支付購物車數(shù)據(jù)
$mysqlCart = Cart::find()
->where(['user_id'=>Yii::$app->user->identity->id, 'status'=>2])
->asArray()->all();
$goods = [];
$carts = [];
//5 構(gòu)造和cookie相同的數(shù)據(jù)結(jié)構(gòu)
if (!empty($mysqlCart)) {
foreach($mysqlCart as $v){
$carts[$v['goods_id']] = $v['goods_num'];
}
$goods = Goods::findAll(array_keys($carts));
}
}
最后將數(shù)據(jù)返回到頁面當中
return $this->render('cart', [
'goods' => $goods,
'carts' => $carts
]);