一、需求
1、網上商城,收貨地址是必不可少的,這裏大概寫一下用PHP實現收貨地址的添加、修改、刪除
2、Tips
,主要處理收貨地址是否是默認地址,默認地址規則如下
一個用戶只能有1個默認地址
如果用戶只有1個地址,則設置該地址爲默認地址
二、數據表設計
CREATE TABLE `address` (
`id` int(11) NOT NULL AUTO_INCREMENT COMMENT '主鍵自增',
`userId` int(11) NOT NULL DEFAULT '0' COMMENT '用戶ID',
`provinceId` int(11) NOT NULL DEFAULT '0' COMMENT '省ID',
`cityId` int(11) NOT NULL DEFAULT '0' COMMENT '城市ID',
`districtId` int(11) NOT NULL DEFAULT '0' COMMENT '區ID',
`name` varchar(50) NOT NULL DEFAULT '' COMMENT '收貨人姓名',
`tag` enum('家','公司','學校') NOT NULL DEFAULT '家' COMMENT '標籤 不能爲空',
`mobile` varchar(50) NOT NULL DEFAULT '' COMMENT '手機號',
`remark` varchar(255) NOT NULL DEFAULT '' COMMENT '詳細地址(最少5個字符)',
`isDefault` tinyint(1) NOT NULL DEFAULT '0' COMMENT '是否是默認地址 1是 0否 默認否',
`createTime` int(10) NOT NULL DEFAULT '0' COMMENT '創建時間',
`updateTime` int(10) NOT NULL DEFAULT '0' COMMENT '更新時間',
`createUser` int(11) NOT NULL DEFAULT '0' COMMENT '創建人',
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
三、代碼
1、數據
$data = [
'userId' => '用戶ID',
'provinceId' => '省ID',
'cityId' => '市ID',
'districtId' => '區ID',
'name' => '收貨人姓名',
'mobile' => '收貨人手機號',
'tag' => '標籤',
'remark' => '詳細地址',
'isDefault' => '是否是默認地址'
];
2、添加
/**
* 地址添加
* @param $data
* @return mixed
*/
public function insert($data) {
$userId = $data['userId'];
$addressDao = new AddressDao();
$result = $addressDao->queryAll(['userId' => $userId]);
if (empty($result)) { //如果是第一個收貨地址:設置爲默認地址
$data['isDefault'] = 1;
}
//如果該地址設置爲了默認地址,並且不是第一個收貨地址;則把之前的所有地址設置爲非默認地址
if (isset($data['isDefault']) && $data['isDefault'] && !empty($result)) {
$addressDao->updateByQuery(['isDefault' => 0], ['userId' => $userId]);
}
return $addressDao->insert($data); //數據添加
}
3、修改
/**
* 地址更新
* @param $data
* @return mixed
*/
public function update($data) {
$addressDao = new AddressDao();
//如果該地址設置爲了默認地址;則把之前的所有地址設置爲非默認地址
if (isset($data['isDefault']) && $data['isDefault']) {
$addressDao->updateByQuery(['isDefault' => 0], ['userId' => $data['userId']]);
}
return $addressDao->update($data);
}
4、刪除
/**
* 刪除、批量刪除
* @param $param ['userId' => 12, 'id' => '1,2,3']
* @return mixed
* @throws \think\Exception
*/
public function del($param){
$userId = $param['userId'];
$ids = explode(',', $param['id']);
$data = [
'id' => ['in', $ids],
'is_deleted' => 1
];
$addressDao = new AddressDao();
$res = $addressDao->update($data); //刪除地址(僞刪除)
if ($res) {
$result = $addressDao->queryAll(['userId' => $userId]); //查詢剩餘地址數量
if (count($result) == 1) { //如果只剩一個地址,則設爲默認地址。
$addressDao->update(['isDefault' => 1, 'id' => $result[0]['id']]);
}
}
return $res;
}
5、tips
- 用戶ID:userId 可以根據當前登錄用戶的token直接獲取,我這裏方便演示就直接寫死在$data裏面了