belongsToMany(Address::class); } public function domain() { return $this->belongsTo(Domain::class); } public function echomail() { return $this->hasMany(Echomail::class) ->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); 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; } }); } /** * Number of messages waiting for address * * @param Address $ao * @return Collection */ public function waiting(Address $ao): Collection { return $this->echomail() ->join('echomail_seenby',['echomail_seenby.echomail_id'=>'echomails.id']) ->whereNull('sent_at') ->whereNotNull('export_at') ->where('address_id',$ao->id) ->get(); } }