UserAddress.php 2.7 KB

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