UserAddress.php 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102
  1. <?php
  2. /**
  3. *
  4. * @author: xaboy<365615158@qq.com>
  5. * @day: 2017/12/25
  6. */
  7. namespace app\models\user;
  8. use crmeb\basic\BaseModel;
  9. use crmeb\traits\ModelTrait;
  10. /**
  11. * TODO 用户收货地址
  12. * Class UserAddress
  13. * @package app\models\user
  14. */
  15. class UserAddress extends BaseModel
  16. {
  17. /**
  18. * 数据表主键
  19. * @var string
  20. */
  21. protected $pk = 'id';
  22. /**
  23. * 模型名称
  24. * @var string
  25. */
  26. protected $name = 'user_address';
  27. use ModelTrait;
  28. protected $insert = ['add_time'];
  29. protected $hidden = ['add_time', 'is_del', 'uid'];
  30. protected function setAddTimeAttr()
  31. {
  32. return time();
  33. }
  34. /**
  35. * 设置默认收货地址
  36. * @param $id 地址id
  37. * @param $uid 用户uid
  38. * @return bool
  39. */
  40. public static function setDefaultAddress($id,$uid)
  41. {
  42. self::beginTrans();
  43. $res1 = self::where('uid',$uid)->update(['is_default'=>0]);
  44. $res2 = self::where('id',$id)->where('uid',$uid)->update(['is_default'=>1]);
  45. $res =$res1 !== false && $res2 !== false;
  46. self::checkTrans($res);
  47. return $res;
  48. }
  49. /**
  50. * 设置用户地址查询初始条件
  51. * @param null $model
  52. * @param string $prefix
  53. * @return \think\Model
  54. */
  55. public static function userValidAddressWhere($model=null,$prefix = '')
  56. {
  57. if($prefix) $prefix .='.';
  58. $model = self::getSelfModel($model);
  59. return $model->where("{$prefix}is_del",0);
  60. }
  61. /**
  62. * 获取用户收货地址并分页
  63. * @param $uid 用户uid
  64. * @param int $page 页码
  65. * @param int $limit 展示条数
  66. * @param string $field 展示字段
  67. * @return array
  68. * @throws \think\db\exception\DataNotFoundException
  69. * @throws \think\db\exception\ModelNotFoundException
  70. * @throws \think\exception\DbException
  71. */
  72. public static function getUserValidAddressList($uid,$page=1,$limit=8,$field = '*')
  73. {
  74. if($page) return self::userValidAddressWhere()->where('uid',$uid)->order('add_time DESC')->field($field)->page((int)$page,(int)$limit)->select()->toArray()?:[];
  75. else return self::userValidAddressWhere()->where('uid',$uid)->order('add_time DESC')->field($field)->select()->toArray()?:[];
  76. }
  77. /**
  78. * 获取用户默认收货地址
  79. * @param $uid 用户uid
  80. * @param string $field 展示字段
  81. * @return array|\think\Model|null
  82. * @throws \think\db\exception\DataNotFoundException
  83. * @throws \think\db\exception\ModelNotFoundException
  84. * @throws \think\exception\DbException
  85. */
  86. public static function getUserDefaultAddress($uid,$field = '*')
  87. {
  88. return self::userValidAddressWhere()->where('uid',$uid)->where('is_default',1)->field($field)->find();
  89. }
  90. }