UserExtend.php 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. <?php
  2. /**
  3. * Created by PhpStorm.
  4. * User: zhengmingwei
  5. * Date: 2020/3/8
  6. * Time: 7:20 PM
  7. */
  8. namespace addons\unishop\model;
  9. use fast\Random;
  10. use think\Db;
  11. use think\Exception;
  12. use think\Model;
  13. /**
  14. * 扩展用户表
  15. * Class UserExtend
  16. * @package addons\unishop\model
  17. */
  18. class UserExtend extends Model
  19. {
  20. // 表名
  21. protected $name = 'unishop_user_extend';
  22. // 开启自动写入时间戳字段
  23. protected $autoWriteTimestamp = 'int';
  24. // 定义时间戳字段名
  25. protected $createTime = 'createtime';
  26. protected $updateTime = 'updatetime';
  27. /**
  28. * 关联基础用户表
  29. */
  30. public function user()
  31. {
  32. return $this->hasOne('user', 'id', 'user_id')->field('id,avatar,mobile,username');
  33. }
  34. /**
  35. * 通过微信小程序openid获取用户id
  36. */
  37. public function getUserInfoByOpenid($openid)
  38. {
  39. $userExtend = $this
  40. ->with('user')
  41. ->where(['openid' => $openid])
  42. ->find();
  43. if ($userExtend) {
  44. $user = $userExtend->user;
  45. } else {
  46. Db::startTrans();
  47. try {
  48. $params = [
  49. 'level' => 1,
  50. 'score' => 0,
  51. 'jointime' => time(),
  52. 'joinip' => $_SERVER['REMOTE_ADDR'],
  53. 'logintime' => time(),
  54. 'loginip' => $_SERVER['REMOTE_ADDR'],
  55. 'prevtime' => time(),
  56. 'status' => 'normal',
  57. 'avatar' => '',
  58. 'username' => __('Tourist')
  59. ];
  60. $user = User::create($params, true);
  61. self::create([
  62. 'user_id' => $user->id,
  63. 'openid' => $openid
  64. ], true);
  65. Db::commit();
  66. } catch (Exception $e) {
  67. Db::rollback();
  68. return false;
  69. }
  70. }
  71. $user = $user->toArray();
  72. return $user;
  73. }
  74. }