Client.php 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. <?php
  2. namespace App\Models;
  3. use Illuminate\Database\Eloquent\Factories\HasFactory;
  4. use Illuminate\Database\Eloquent\Model;
  5. use Illuminate\Database\Eloquent\SoftDeletes;
  6. use Illuminate\Database\Eloquent\Relations\BelongsTo;
  7. use Illuminate\Database\Eloquent\Relations\HasMany;
  8. class Client extends Model
  9. {
  10. use HasFactory, SoftDeletes;
  11. protected $fillable = [
  12. 'document',
  13. 'user_id',
  14. ];
  15. protected $casts = [
  16. 'created_at' => 'datetime',
  17. 'updated_at' => 'datetime',
  18. 'deleted_at' => 'datetime',
  19. ];
  20. /**
  21. * @return BelongsTo
  22. */
  23. public function user(): BelongsTo
  24. {
  25. return $this->belongsTo(User::class);
  26. }
  27. /**
  28. * @return HasMany
  29. */
  30. public function blockedByProviders(): HasMany
  31. {
  32. return $this->hasMany(ProviderClientBlock::class);
  33. }
  34. /**
  35. * @return HasMany
  36. */
  37. public function blockedProviders(): HasMany
  38. {
  39. return $this->hasMany(ClientProviderBlock::class);
  40. }
  41. public function updateAverageRating(float $newRating): void
  42. {
  43. $totalReviews = Review::where('reviews.origin', 'provider')
  44. ->leftJoin('schedules', 'schedules.id', '=', 'reviews.schedule_id')
  45. ->where('schedules.client_id', $this->id)
  46. ->count();
  47. if ($totalReviews === 0) {
  48. $this->average_rating = $newRating;
  49. } else {
  50. $currentTotalRating = $this->average_rating * ($totalReviews - 1);
  51. $newAverage = ($currentTotalRating + $newRating) / $totalReviews;
  52. $this->average_rating = round($newAverage, 2);
  53. }
  54. $this->save();
  55. }
  56. public function schedules()
  57. {
  58. return $this->hasMany(Schedule::class);
  59. }
  60. }