PublicRankingUser.php 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  1. <?php
  2. /**
  3. * 重庆赤晓店信息科技有限公司
  4. * https://www.chixiaodian.com
  5. * Copyright (c) 2025 赤店商城 All rights reserved.
  6. */
  7. namespace app\models;
  8. use Yii;
  9. use yii\behaviors\TimestampBehavior;
  10. use yii\db\ActiveRecord;
  11. class PublicRankingUser extends \yii\db\ActiveRecord
  12. {
  13. /**
  14. * @inheritdoc
  15. */
  16. public static function tableName()
  17. {
  18. return '{{%public_ranking_user}}';
  19. }
  20. public function behaviors()
  21. {
  22. return [
  23. [
  24. // 自动更新创建和更新时间
  25. 'class' => TimestampBehavior::class,
  26. ]
  27. ];
  28. }
  29. public static function initUser($store_id, $user_id, $order) {
  30. $has = PublicRankingUser::findOne(['user_id' => $user_id]);
  31. if($has){
  32. return [
  33. 'code' => 0,
  34. 'data' => $has,
  35. ];
  36. }
  37. return PublicRankingUser::add($store_id, $user_id, $order);
  38. }
  39. public static function add($store_id, $user_id, $order) {
  40. try{
  41. $has = self::findOne(['user_id' => $user_id]);
  42. if($has){
  43. return [
  44. 'code' => 0,
  45. 'data' => $has,
  46. ];
  47. }
  48. $max = (int)self::find()->where(['store_id' => $store_id])->max('sort');
  49. $model = new self([
  50. 'store_id' => $store_id,
  51. 'user_id' => $user_id,
  52. 'sort' => $max + 1,
  53. ]);
  54. $model->first_order_id = (int)$order['id'];
  55. $model->first_order_time = (int)$order['created_at'];
  56. if(!$model->save()){
  57. throw new \Exception('数据保存错误:' . array_shift($model->getFirstErrors()));
  58. }
  59. return [
  60. 'code' => 0,
  61. 'data' => $model,
  62. ];
  63. } catch (\Exception $ex) {
  64. debug_log([$store_id, $user_id, $ex->getMessage()], __CLASS__);
  65. \Yii::error($ex);
  66. return [
  67. 'code' => 1,
  68. 'msg' => $ex->getMessage(),
  69. ];
  70. }
  71. }
  72. public static function getUpperLevelsKaryTree($current, $k) {
  73. $upperLevels = [];
  74. while ($current > 0) {
  75. $upper = floor(($current - 1) / $k); // 上级排号
  76. if($upper <= 0){
  77. break;
  78. }
  79. $upperLevels[] = $upper;
  80. $current = $upper;
  81. }
  82. return $upperLevels;
  83. }
  84. public static function getParentSorts($sort, $PublicRankingRow, $count) {
  85. $sorts = self::getUpperLevelsKaryTree($sort, $PublicRankingRow);
  86. $ret = array_slice($sorts, 0, $count);
  87. return $ret;
  88. }
  89. }