Browse Source

Merge branch 'filter-asset-index' into dev

kely 9 months ago
parent
commit
252ff7eb2e
2 changed files with 24 additions and 21 deletions
  1. 14 7
      app/Http/Controllers/API/AssetController.php
  2. 10 14
      app/Models/Asset.php

+ 14 - 7
app/Http/Controllers/API/AssetController.php

@@ -20,15 +20,22 @@ class AssetController extends Controller
      */
     public function index(Request $request)
     {
-        $pageSize=$request->get('page_size') ?? 10;
-        $assets = Asset::filter($request->all())
-            ->where("parent_id", 0)
+        $fullAsset=[];
+        $paths = Asset::filter($request->all())
             ->where('company_id',Auth::user()->company_id)
-            ->allowed()
-            ->with(['children','children.children'])
-            ->paginate($pageSize);
+            ->allowed()->pluck('path')->toArray();
+
+            foreach ($paths as $path){
+                $parentAssets = explode(',', substr($path, 1, -1));
+                $fullAsset=  array_merge($parentAssets,$fullAsset);
+            }
+
+        $resultAssets = Asset::whereIn('id', $fullAsset)->get()->each(function ($asset) {
+            $asset->requirement_total = $asset->total_requirements_count;
+            $asset->plan_total = $asset->total_plans_count;
+        });
+        return make_tree($resultAssets->toArray());
 
-        return AssetResource::collection($assets);
     }
 
     /**

+ 10 - 14
app/Models/Asset.php

@@ -64,25 +64,21 @@ class Asset extends Model
     //获取子级需求数量
     public function getTotalRequirementsCountAttribute()
     {
-        $totalRequirementsCount = $this->requirements()->count(); // 当前资产的需求数量
-
-        foreach ($this->children as $child) {
-            $totalRequirementsCount += $child->getTotalRequirementsCountAttribute(); // 递归调用子资产的方法
-        }
-
-        return  $totalRequirementsCount;
+        $childIds = [];
+        Asset::where('path','like','%,'.$this->id.',%')->get('id')->each(function ($id)use (&$childIds){
+            $childIds[]=$id['id'];
+        });
+        return Requirement::whereIn('asset_id',$childIds)->count();
     }
 
     //获取子级计划数量
     public function getTotalPlansCountAttribute()
     {
-        $totalPlansCount = $this->plans()->count(); // 当前资产的需求数量
-
-        foreach ($this->children as $child) {
-            $totalPlansCount += $child->getTotalPlansCountAttribute(); // 递归调用子资产的方法
-        }
-
-        return  $totalPlansCount;
+        $childIds = [];
+        Asset::where('path','like','%,'.$this->id.',%')->get('id')->each(function ($id)use (&$childIds){
+            $childIds[]=$id['id'];
+        });
+        return Plan::whereIn('asset_id',$childIds)->count();
     }
 
     public function library(){