Query optimisations for last_messages and traffic
This commit is contained in:
@@ -6,16 +6,18 @@ use Carbon\Carbon;
|
||||
use Illuminate\Database\Eloquent\Collection;
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
use Illuminate\Database\Eloquent\SoftDeletes;
|
||||
use Illuminate\Support\Facades\Cache;
|
||||
use Rennokki\QueryCache\Traits\QueryCacheable;
|
||||
|
||||
use App\Traits\ScopeActive;
|
||||
|
||||
class Echoarea extends Model
|
||||
{
|
||||
use SoftDeletes,ScopeActive;
|
||||
use SoftDeletes,ScopeActive,QueryCacheable;
|
||||
|
||||
private const CACHE_TIME = 3600;
|
||||
|
||||
protected $dates = [ 'last_message' ];
|
||||
|
||||
/* RELATIONS */
|
||||
|
||||
public function addresses()
|
||||
@@ -34,31 +36,30 @@ class Echoarea extends Model
|
||||
->orderBy('datetime','ASC');
|
||||
}
|
||||
|
||||
/* ATTRIBUTES */
|
||||
|
||||
public function getLastMessageAttribute(): ?Carbon
|
||||
{
|
||||
return $this->echomail?->last()->datetime;
|
||||
}
|
||||
|
||||
/* METHODS */
|
||||
|
||||
public function messages_count(int $period): int
|
||||
{
|
||||
$key = sprintf('%s_%d_%d','echo_messages_count',$this->id,$period);
|
||||
$eo = Echomail::cacheFor(self::CACHE_TIME)
|
||||
->where('echoarea_id',$this->id);
|
||||
|
||||
return Cache::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;
|
||||
}
|
||||
});
|
||||
$dt = Carbon::now()->startOfday();
|
||||
|
||||
switch ($period) {
|
||||
case 1: // day
|
||||
$eo->where('datetime','>=',$dt->subDay());
|
||||
break;
|
||||
case 7: // week
|
||||
$eo->where('datetime','>=',$dt->subWeek());
|
||||
break;
|
||||
case 30: // month
|
||||
$eo->where('datetime','>=',$dt->subMonth());
|
||||
break;
|
||||
default:
|
||||
return 0;
|
||||
}
|
||||
|
||||
return $eo->count();
|
||||
}
|
||||
|
||||
/**
|
||||
|
Reference in New Issue
Block a user