RequirementFilter.php 2.0 KB

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