* @date 2020/6/30 16:45 * * @return \think\response\Json * @throws \Lettered\Support\Exceptions\FailedException * @throws \think\db\exception\DataNotFoundException * @throws \think\db\exception\ModelNotFoundException * @throws \think\exception\DbException */ public function index(){ $model = model('common/UsersAddr') ->where(['user_id' => $this->auth->user()->id]); // 加载默认数据 if (input('default') != ""){ $model->where(['default' => 1]); return $this->ApiJson(0,'OK!', $model->find()); } $addr = $model->order('default','desc')->select(); return $this->ApiJson(0,'OK!', $addr); } /** * 新增数据 * * @author 许祖兴 < zuxing.xu@lettered.cn> * @date 2020/7/7 18:27 * * @return \think\response\Json * @throws \Lettered\Support\Exceptions\FailedException */ public function save() { // 接收数据 $params = $this->request->param(); // 数据校验 $valid = $this->validate($params, [ 'name|姓名' => 'require', 'mobile|手机号' => 'require', 'province|省份' => 'require', 'city|城市' => 'require', 'country|县区' => 'require', 'detail|地址详细信息' => 'require', ]); // 错误返回 if(true !== $valid){ return $this->ApiJson(-1, $valid); }; // 追加数据 $params['user_id'] = $this->auth->user()['id']; $params['default'] = $params['default'] == 'true' ? 1 : 0; $ret = model('common/UsersAddr')->storeBy($params); if ($ret){ // 默认处理 if ($params['default']){ model('common/UsersAddr') ->where(['user_id' => $this->auth->user()['id']]) ->where('id','<>' , $ret) ->update(['default' => 0]); } return $this->ApiJson(0,"新增成功"); } return $this->ApiJson(-1,"数据异常,请稍后重试"); } /** * 地址更新 * * @author 许祖兴 < zuxing.xu@lettered.cn> * @date 2020/7/1 8:50 * * @param $id * @return \think\response\Json * @throws \Lettered\Support\Exceptions\FailedException * @throws \think\Exception * @throws \think\exception\PDOException */ public function update($id) { (new IDMustBePositiveInt())->valid(); // 接收数据 $params = $this->request->param(); // 查询 $addr = model('common/UsersAddr')->findBy($id); // 数据校验 $valid = $this->validate($params, [ 'name|姓名' => 'require', 'mobile|手机号' => 'require', 'province|省份' => 'require', 'city|城市' => 'require', 'country|县区' => 'require', 'detail|地址详细信息' => 'require', ]); // 错误返回 if(true !== $valid){ return $this->ApiJson(-1, $valid); }; $params['default'] = $params['default'] == 'true' ? 1 : 0; // 更新 $ret = $addr->updateBy($id, $params); // 默认处理 if ($params['default'] == 1 && $params['default'] != $addr['default']){ model('common/UsersAddr') ->where(['user_id' => $this->auth->user()['id']]) ->where('id','<>' , $id) ->update(['default' => 0]); } if ($ret){ return $this->ApiJson(0,"更新成功"); } return $this->ApiJson(-1,"数据异常,请稍后重试"); } /** * 删除地址 * * @author 许祖兴 < zuxing.xu@lettered.cn> * @date 2020/7/2 11:32 * * @param $id * @return \think\response\Json * @throws \Lettered\Support\Exceptions\EvidentException */ public function delete($id) { (new IDMustBePositiveInt())->valid(); $ret = model('common/UsersAddr')->deleteBy($id); if ($ret){ return $this->ApiJson(0,"删除地址成功"); } return $this->ApiJson(-1,"数据异常,请稍后重试"); } }