UserAddress.php
3.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
<?php
namespace app\common\model;
use think\Model;
class UserAddress extends Model
{
/**
* 隐藏字段
* @var array
*/
protected $hidden = [
'createtime',
'updatetime'
];
/**
* 追加字段
* @var array
*/
protected $append = [
'area',
'user_address_id'
];
/**
* 新增user_address_id(目的:方便前端 待支付订单修改地址)
*/
public function getUserAddressIdAttr($value, $data)
{
return $data['id'];
}
/**
* 地区名称
*/
public function getAreaAttr($value, $data)
{
return Area::getNameById($data['province_id']).','.Area::getNameById($data['city_id']).','.Area::getNameById($data['district_id']);
}
/**
* 地址列表
*/
public static function addressList($user_id)
{
return self::all(compact('user_id'));
}
/**
* 新增收货地址
*/
public function add($user, $data)
{
empty($data['isdefault']) && $data['isdefault'] = '0';
// 添加收货地址
$area = explode(',', $data['area']);
$province_id = Area::getIdByName($area[0], 1);
$city_id = Area::getIdByName($area[1], 2, $province_id);
$district_id = Area::getIdByName($area[2], 3, $city_id);
// 该地址设为默认,其他地址就设为非默认
if($data['isdefault'] == '1'){
$this->where('user_id',$user['id'])->update(['isdefault'=>'0']);
}
$this->allowField(true)->save(array_merge([
'user_id' => $user['id'],
'province_id' => $province_id,
'city_id' => $city_id,
'district_id' => $district_id
], $data));
// 没有默认收货地址,就把该收货地址设为默认
!$this->get(['user_id'=>$user['id'],'isdefault'=>'1']) && self::update(['id'=>$this['id'],'isdefault'=>'1']);
return true;
}
/**
* 编辑收货地址
*/
public function edit($data)
{
empty($data['isdefault']) && $data['isdefault'] = '0';
// 添加收货地址
$area = explode(',', $data['area']);
$province_id = Area::getIdByName($area[0], 1);
$city_id = Area::getIdByName($area[1], 2, $province_id);
$district_id = Area::getIdByName($area[2], 3, $city_id);
// 该地址设为默认,其他地址就设为非默认
if($data['isdefault'] == '1'){
self::where('user_id',$this['user_id'])->update(['isdefault'=>'0']);
$data['isdefault'] = 1;
}
return $this->allowField(true)
->save(array_merge(compact('province_id', 'city_id', 'district_id'), $data));
}
/**
* 删除收货地址
*/
public function remove($user)
{
// 查询当前是否为默认地址
if($this['isdefault'] == '1'){
$this->delete();
$address = $this->get(['user_id'=>$user['id']]);
$address->isdefault = "1";
$address->save();
}else{
$this->delete();
}
return true;
}
/**
* 设置为默认
*/
public function setDefault()
{
$this->where('user_id',$this['user_id'])->update(['isdefault'=>'0']);
$this->update(['id'=>$this['id'],'isdefault'=>'1']);
return true;
}
/**
* 收货地址详情
*/
public static function detail($user_id, $id)
{
return self::get(compact('user_id', 'id'));
}
}