where('user_id', $this->uid()) ->order('is_default desc,id desc') ->select(); $this->success('', ['list' => $list]); } /** * 地址详情 */ public function detail() { $id = (int)$this->request->param('id'); $row = Db::name('address')->where('id', $id)->where('user_id', $this->uid())->find(); if (!$row) { $this->error('地址不存在'); } $this->success('', ['detail' => $row]); } /** * 新增 / 编辑地址 * @ApiMethod (POST) */ public function save() { $id = (int)$this->request->post('id', 0); $data = [ 'contact' => trim((string)$this->request->post('contact')), 'mobile' => trim((string)$this->request->post('mobile')), 'province' => trim((string)$this->request->post('province')), 'city' => trim((string)$this->request->post('city')), 'district' => trim((string)$this->request->post('district')), 'address' => trim((string)$this->request->post('address')), 'lng' => trim((string)$this->request->post('lng')), 'lat' => trim((string)$this->request->post('lat')), 'floor' => max(1, (int)$this->request->post('floor', 1)), 'has_elevator' => (int)$this->request->post('has_elevator', 1), 'is_default' => (int)$this->request->post('is_default', 0), 'updatetime' => time(), ]; if ($data['contact'] === '' || $data['mobile'] === '' || $data['address'] === '') { $this->error('请填写联系人、手机号和详细地址'); } if (!preg_match('/^1\d{10}$/', $data['mobile'])) { $this->error('手机号格式不正确'); } if ($id > 0) { $exist = Db::name('address')->where('id', $id)->where('user_id', $this->uid())->find(); if (!$exist) { $this->error('地址不存在'); } Db::name('address')->where('id', $id)->update($data); } else { $count = Db::name('address')->where('user_id', $this->uid())->count(); if ($count >= 20) { $this->error('最多保存 20 个地址'); } $data['user_id'] = $this->uid(); $data['createtime'] = time(); if ($count === 0) { $data['is_default'] = 1; } $id = Db::name('address')->insertGetId($data); } if ($data['is_default'] === 1) { Db::name('address')->where('user_id', $this->uid())->where('id', '<>', $id)->update(['is_default' => 0]); } $this->success('保存成功', ['id' => (int)$id]); } /** * 设为默认 * @ApiMethod (POST) */ public function setDefault() { $id = (int)$this->request->post('id'); $exist = Db::name('address')->where('id', $id)->where('user_id', $this->uid())->find(); if (!$exist) { $this->error('地址不存在'); } Db::name('address')->where('user_id', $this->uid())->update(['is_default' => 0]); Db::name('address')->where('id', $id)->update(['is_default' => 1]); $this->success('已设为默认'); } /** * 删除地址 * @ApiMethod (POST) */ public function delete() { $id = (int)$this->request->post('id'); $exist = Db::name('address')->where('id', $id)->where('user_id', $this->uid())->find(); if (!$exist) { $this->error('地址不存在'); } Db::name('address')->where('id', $id)->delete(); $this->success('已删除'); } }