优化数据

This commit is contained in:
2021-07-05 17:11:02 +08:00
parent 74732188c9
commit 06ca4a9ec3
2 changed files with 61 additions and 14 deletions

View File

@@ -7,8 +7,10 @@ use App\Models\Traits\HasArea;
use DateTimeInterface;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Str;
use RuLong\Identity\Traits\UserHasIdentity;
use Illuminate\Support\Facades\Cache;
class User extends Authenticatable
{
@@ -128,22 +130,67 @@ class User extends Authenticatable
/**
* 关联平安卡券核销
* @author 玄尘 2020-04-03
* @return [type] [description]
* @return \Illuminate\Database\Eloquent\Relations\HasMany [type] [description]
*/
public function coupons()
{
return $this->hasMany(Coupon::class);
}
/**
* Notes: description
* @Author: 玄尘
* @Date : 2021/7/5 17:00
* @param $type
* @param string $date
* @return int
*/
public function getCouponCount($type, $date = '')
{
return $this->coupons()
->whereIn('status', [2])
->where('thirdPartyGoodsId', $type)
->when($date, function ($q) {
$q->whereDate('created_at', now()->format('Y-m-d'));
})
->count();
$data = $this->checkCouponCount($date);
return $data[$type] ?? 0;
// return $this->coupons()
// ->whereIn('status', [2])
// ->where('thirdPartyGoodsId', $type)
// ->when($date, function ($q) {
// $q->whereDate('created_at', now()->format('Y-m-d'));
// })
// ->count();
}
/**
* Notes: 一次性设置用户数据
* @Author: 玄尘
* @Date : 2021/7/5 17:01
* @param $date
* @return array|mixed
*/
public function checkCouponCount($date)
{
$date = $date ? 'today' : 'all';
$name = "user_{$this->id}_coupon_count_date_{$date}";
if (Cache::has($name)) {
return Cache::get($name, []);
} else {
$res = DB::table('coupons')
->where('user_id', $this->id)
->whereIn('status', [2])
->when($date, function ($q) {
$q->whereDate('created_at', now()->format('Y-m-d'));
})
->select('thirdPartyGoodsId', DB::raw('count(*) as total'))
->groupBy('thirdPartyGoodsId')
->get()
->pluck('total', 'thirdPartyGoodsId')
->toArray();
Cache::put($name, $res, 10);
return $res;
}
}
}