Просмотр файла app/Models/Message.php

Размер файла: 2.72Kb
  1. <?php
  2.  
  3. declare(strict_types=1);
  4.  
  5. namespace App\Models;
  6.  
  7. use App\Traits\UploadTrait;
  8. use Illuminate\Database\Eloquent\Builder;
  9. use Illuminate\Database\Eloquent\Model;
  10. use Illuminate\Database\Eloquent\Relations\BelongsTo;
  11. use Illuminate\Database\Eloquent\Relations\MorphMany;
  12.  
  13. /**
  14. * Class Inbox
  15. *
  16. * @property int id
  17. * @property int user_id
  18. * @property int author_id
  19. * @property string text
  20. * @property int created_at
  21. */
  22. class Message extends BaseModel
  23. {
  24. use UploadTrait;
  25.  
  26. public const IN = 'in'; // Принятые
  27. public const OUT = 'out'; // Отправленные
  28.  
  29. /**
  30. * Indicates if the model should be timestamped.
  31. *
  32. * @var bool
  33. */
  34. public $timestamps = false;
  35.  
  36. /**
  37. * The attributes that aren't mass assignable.
  38. *
  39. * @var array
  40. */
  41. protected $guarded = [];
  42.  
  43. /**
  44. * Morph name
  45. *
  46. * @var string
  47. */
  48. public static $morphName = 'messages';
  49.  
  50. /**
  51. * Директория загрузки файлов
  52. *
  53. * @var string
  54. */
  55. public $uploadPath = '/uploads/messages';
  56.  
  57. /**
  58. * Возвращает связь пользователей
  59. *
  60. * @return BelongsTo
  61. */
  62. public function author(): BelongsTo
  63. {
  64. return $this->belongsTo(User::class, 'author_id')->withDefault();
  65. }
  66.  
  67. /**
  68. * Возвращает загруженные файлы
  69. *
  70. * @return MorphMany
  71. */
  72. public function files(): MorphMany
  73. {
  74. return $this->morphMany(File::class, 'relate');
  75. }
  76.  
  77. /**
  78. * Create dialogue
  79. *
  80. * @param User $user
  81. * @param User|null $author
  82. * @param string $text
  83. * @param bool $withAuthor
  84. *
  85. * @return Builder|Model
  86. */
  87. public function createDialogue(User $user, ?User $author, string $text, bool $withAuthor)
  88. {
  89. $authorId = $author->id ?? 0;
  90.  
  91. $message = self::query()->create([
  92. 'user_id' => $user->id,
  93. 'author_id' => $authorId,
  94. 'text' => $text,
  95. 'created_at' => SITETIME,
  96. ]);
  97.  
  98. Dialogue::query()->create([
  99. 'message_id' => $message->id,
  100. 'user_id' => $user->id,
  101. 'author_id' => $authorId,
  102. 'type' => self::IN,
  103. 'created_at' => SITETIME,
  104. ]);
  105.  
  106. if ($authorId && $withAuthor) {
  107. Dialogue::query()->create([
  108. 'message_id' => $message->id,
  109. 'user_id' => $authorId,
  110. 'author_id' => $user->id,
  111. 'type' => self::OUT,
  112. 'reading' => 1,
  113. 'created_at' => SITETIME,
  114. ]);
  115. }
  116.  
  117. $user->increment('newprivat');
  118.  
  119. return $message;
  120. }
  121. }