Cache some calls to Mongo for performance
This commit is contained in:
@@ -2,15 +2,18 @@
|
||||
|
||||
namespace App\Models;
|
||||
|
||||
use Carbon\Carbon;
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
use Illuminate\Database\Eloquent\SoftDeletes;
|
||||
|
||||
use Illuminate\Support\Facades\Cache;
|
||||
use App\Traits\{ScopeActive,UsePostgres};
|
||||
|
||||
class Echoarea extends Model
|
||||
{
|
||||
use SoftDeletes,ScopeActive,UsePostgres;
|
||||
|
||||
private const CACHE_TIME = 3600;
|
||||
|
||||
/* RELATIONS */
|
||||
|
||||
public function addresses()
|
||||
@@ -28,4 +31,35 @@ class Echoarea extends Model
|
||||
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;
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
Reference in New Issue
Block a user