UserAddress.php 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. <?php
  2. namespace app\common\model;
  3. use think\db\Query;
  4. use think\Model;
  5. /**
  6. * 会员模型
  7. * @method Query|self exists($data)
  8. */
  9. class UserAddress extends Model
  10. {
  11. public function user(){
  12. return $this->belongsTo(User::class);
  13. }
  14. protected static function init()
  15. {
  16. self::beforeWrite(function (self $address){
  17. if(empty($address['city'])) {
  18. $address['city'] = tm()->getLocation($address['longitude'], $address['latitude'])['city'];
  19. }
  20. if(!isset($address['is_default'])){
  21. $address['is_default']=0;
  22. }
  23. });
  24. self::afterWrite(function (self $address){
  25. if($address['is_default']==1){
  26. self::where('user_id',$address['user_id'])->where('id','<>',$address['id'])->update(['is_default'=>0]);
  27. }
  28. });
  29. self::beforeInsert(function (self $address){
  30. if(empty($address['location'])){
  31. $address['location']=tm()->getLocation($address['longitude'],$address['latitude'])['address'];
  32. }
  33. });
  34. }
  35. public function scopeExists(Query $query,$data){
  36. if(!empty($data['name'])){
  37. $query->where('name',$data['name']);
  38. }
  39. if(!empty($data['mobile'])){
  40. $query->where('mobile',$data['mobile']);
  41. }
  42. if(!empty($data['address'])){
  43. $query->where('address',$data['address']);
  44. }
  45. if(!empty($data['city'])){
  46. $query->where('city',$data['city']);
  47. }
  48. if(!empty($data['longitude'])){
  49. $query->where('longitude',$data['longitude']);
  50. }
  51. if(!empty($data['latitude'])){
  52. $query->where('latitude',$data['latitude']);
  53. }
  54. }
  55. }