PlanFilter.php 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. <?php
  2. namespace App\ModelFilters;
  3. use App\Models\Asset;
  4. use Carbon\Carbon;
  5. use EloquentFilter\ModelFilter;
  6. class PlanFilter extends ModelFilter
  7. {
  8. /**
  9. * Related Models that have ModelFilters as well as the method on the ModelFilter
  10. * As [relationMethod => [input_key1, input_key2]].
  11. *
  12. * @var array
  13. */
  14. public $relations = [];
  15. public function apply($query)
  16. {
  17. return $query;
  18. }
  19. public function assetId($assetId)
  20. {
  21. $asset = Asset::find($assetId);
  22. if (!$asset || !$asset->children()->first()) {
  23. // 如果没有子级,只返回该分组的需求
  24. return $this->where('asset_id', $assetId);
  25. }
  26. $allRelatedIds = $this->getAllRelatedIds($assetId);
  27. array_push($allRelatedIds, $asset->id);
  28. //把父级id去重
  29. $unIds=array_unique($allRelatedIds);
  30. return $this->whereIn('asset_id',$unIds);
  31. }
  32. private function getAllRelatedIds($assetId)
  33. {
  34. $asset = Asset::find($assetId);
  35. //$group = RequirementGroup::find($groupId);
  36. if (!$asset) {
  37. return [];
  38. }
  39. // 获取所有子级ID
  40. $childIds = $asset->children()->pluck('id')->toArray();
  41. // 递归获取所有子级的子级ID
  42. foreach ($childIds as $childId) {
  43. $childIds = array_merge($childIds, $this->getAllRelatedIds($childId));
  44. }
  45. return $childIds;
  46. }
  47. public function expired($expired): PlanFilter
  48. {
  49. if (! in_array($expired, ['yes', 'no'])) {
  50. return $this;
  51. }
  52. return $this->when($expired == "yes", function ($query) {
  53. return $query->where('end', "<=", Carbon::now()->toDateString());
  54. })->when($expired == "no", function ($query) {
  55. return $query->where('end', ">", Carbon::now()->toDateString())->orWhereNull('end');
  56. });
  57. }
  58. }