ReactionStatusResource.php 1.1 KB

12345678910111213141516171819202122232425262728293031323334353637
  1. <?php
  2. namespace App\Http\Resources\V3;
  3. use App\Models\Reaction;
  4. use Illuminate\Http\Request;
  5. /**
  6. * 一条 reaction 操作后的状态:type + 全局计数 + 是否选中 + 记录 id。
  7. *
  8. * 组装成品是 Resource 的职责:控制器只把 Reaction 模型传进来(store 后是
  9. * 已保存的模型,destroy 后是已删除的模型),count / selected / id 都在这里算。
  10. * selected 直接取模型的 exists 状态——store 后为 true,delete 后为 false。
  11. */
  12. class ReactionStatusResource extends BaseResource
  13. {
  14. /**
  15. * @param Request $request
  16. * @return array{
  17. * type: string,
  18. * count: int,
  19. * selected: bool,
  20. * id: string|null
  21. * }
  22. */
  23. public function toArray($request): array
  24. {
  25. return [
  26. 'type' => $this->type,
  27. 'count' => Reaction::where('target_id', $this->target_id)
  28. ->where('type', $this->type)
  29. ->count(),
  30. 'selected' => $this->exists,
  31. 'id' => $this->exists ? $this->id : null,
  32. ];
  33. }
  34. }