clrghouz/app/Models/Echoarea.php

65 lines
1.5 KiB
PHP
Raw Normal View History

2021-08-11 13:45:30 +00:00
<?php
namespace App\Models;
use Carbon\Carbon;
2021-08-11 13:45:30 +00:00
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Support\Facades\Cache;
2021-09-06 13:39:32 +00:00
use App\Traits\{ScopeActive,UsePostgres};
2021-08-11 13:45:30 +00:00
class Echoarea extends Model
{
2021-09-06 13:39:32 +00:00
use SoftDeletes,ScopeActive,UsePostgres;
2021-08-11 13:45:30 +00:00
private const CACHE_TIME = 3600;
2021-08-11 13:45:30 +00:00
/* RELATIONS */
public function addresses()
{
return $this->belongsToMany(Address::class);
}
public function domain()
{
return $this->belongsTo(Domain::class);
}
public function echomail()
{
return Echomail::select('*')
->where('echoarea_id',$this->id);
}
/* ATTRIBUTES */
public function getLastMessageAttribute(): ?Carbon
{
$key = sprintf('%s_%d','echo_last_message',$this->id);
return Cache::driver('redis')->remember($key,self::CACHE_TIME,function() {
return ($x=$this->echomail()->orderBy('datetime','DESC')->first()) ? $x->datetime : NULL;
});
}
/* METHODS */
public function messages_count(int $period): int
{
$key = sprintf('%s_%d_%d','echo_mesages_count',$this->id,$period);
return Cache::driver('redis')->remember($key,self::CACHE_TIME,function() use ($period) {
switch ($period) {
case 1: // day
return $this->echomail()->where('datetime','>=',Carbon::now()->startOfday()->subDay())->count();
case 7: // week
return $this->echomail()->where('datetime','>=',Carbon::now()->startOfday()->subWeek())->count();
case 30: // month
return $this->echomail()->where('datetime','>=',Carbon::now()->startOfday()->subMonth())->count();
default:
return 0;
}
});
}
2021-08-11 13:45:30 +00:00
}