RequirementFilter.php 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. <?php
  2. namespace App\ModelFilters;
  3. use App\Models\Requirement;
  4. use App\Models\RequirementGroup;
  5. use EloquentFilter\ModelFilter;
  6. class RequirementFilter 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 plan($plan_id){
  20. return $this->where('plan_id',$plan_id);
  21. }
  22. public function assetId($assetId){
  23. return $this->where('asset_id',$assetId);
  24. }
  25. public function groupId($groupId){
  26. //
  27. $group = RequirementGroup::find($groupId);
  28. if (!$group || !$group->children()->first()) {
  29. // 如果没有子级,只返回该分组的需求
  30. return $this->where('requirement_group_id', $groupId);
  31. }
  32. $allRelatedGroupIds = $this->getAllRelatedGroupIds($groupId);
  33. //把父级id去重
  34. $unIds=array_unique($allRelatedGroupIds);
  35. return $this->whereIn('requirement_group_id',$unIds);
  36. }
  37. private function getAllRelatedGroupIds($groupId)
  38. {
  39. $group = RequirementGroup::find($groupId);
  40. if (!$group) {
  41. return [];
  42. }
  43. // 获取所有子级ID
  44. $childIds = $group->children()->pluck('id')->toArray();
  45. // 递归获取所有子级的子级ID
  46. foreach ($childIds as $childId) {
  47. $childIds = array_merge($childIds, $this->getAllRelatedGroupIds($childId));
  48. }
  49. // 添加父级ID(如果需要的话)
  50. if ($group->parent_id) {
  51. $childIds[] = $group->parent_id;
  52. }
  53. return $childIds;
  54. }
  55. }