UserAddress.php 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. <?php
  2. namespace app\common\model;
  3. use fast\Arr;
  4. use think\db\Query;
  5. use think\Model;
  6. /**
  7. * 会员模型
  8. * @method Query|self exists($data)
  9. * @property string city_detail
  10. */
  11. class UserAddress extends Model
  12. {
  13. protected $append=[
  14. ];
  15. public function user(){
  16. return $this->belongsTo(User::class);
  17. }
  18. protected static function init()
  19. {
  20. self::beforeWrite(function (self $address){
  21. /*if(empty($address['city'])) {
  22. $address['city'] = tm()->getLocation($address['longitude'], $address['latitude'])['city'];
  23. }*/
  24. if(!isset($address['is_default'])){
  25. $address['is_default']=0;
  26. }
  27. $address['area']=implode(',',Area::getTreeId($address['city']));
  28. $address['full_address']=Area::getNameString($address['area']).$address['address'];
  29. });
  30. self::afterWrite(function (self $address){
  31. if($address['is_default']==1){
  32. self::where('user_id',$address['user_id'])->where('id','<>',$address['id'])->update(['is_default'=>0]);
  33. }
  34. });
  35. self::beforeInsert(function (self $address){
  36. /*if(empty($address['location'])){
  37. $address['location']=tm()->getLocation($address['longitude'],$address['latitude'])['address'];
  38. }*/
  39. });
  40. }
  41. public function scopeExists(Query $query,$data){
  42. if(!empty($data['name'])){
  43. $query->where('name',$data['name']);
  44. }
  45. if(!empty($data['mobile'])){
  46. $query->where('mobile',$data['mobile']);
  47. }
  48. if(!empty($data['address'])){
  49. $query->where('address',$data['address']);
  50. }
  51. if(!empty($data['city'])){
  52. $query->where('city',$data['city']);
  53. }
  54. if(!empty($data['longitude'])){
  55. $query->where('longitude',$data['longitude']);
  56. }
  57. if(!empty($data['latitude'])){
  58. $query->where('latitude',$data['latitude']);
  59. }
  60. }
  61. public function getCityDetailAttr($a,$b){
  62. $city=$b['city'];
  63. if(!$city){
  64. return '';
  65. }
  66. $area=Area::where('id|name|shortname',$city)->find();
  67. return $area['mergename']??'';
  68. }
  69. public function orderAddress(){
  70. return [
  71. 'name'=>$this['name'],
  72. 'mobile'=>$this['mobile'],
  73. 'address'=>$this['full_address'],
  74. 'city'=>$this['city'],
  75. 'area'=>$this['area'],
  76. ];
  77. }
  78. }