PHP 收货地址:添加、修改、删除

    技术2022-07-10  155

    目录

    一、需求二、数据表设计三、代码1、数据2、添加3、修改4、删除5、tips

    一、需求

    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里面了
    Processed: 0.015, SQL: 9