Browse Source

资产添加树形结构

kely 1 year ago
parent
commit
3aa7a9d298

+ 14 - 0
app/Http/Requests/API/Asset/CreateOrUpdateRequest.php

@@ -66,9 +66,23 @@ class CreateOrUpdateRequest extends FormRequest
             ],
             'latitude' => 'numeric',
             'longitude' => 'numeric',
+            'parent_id' => [
+                $this->parentIdExistsRule(),
+            ]
         ];
     }
 
+    protected function parentIdExistsRule()
+    {
+        // 如果 parent_id 不为 0,返回 exists 规则
+        if ($this->input('parent_id') != 0) {
+            return Rule::exists('assets', 'id')->where($this->userCompanyWhere());
+        }
+
+        // 如果 parent_id 为 0,返回空数组以跳过 exists 验证
+        return [];
+    }
+
     public function attributes()
     {
         return [

+ 2 - 0
app/Http/Resources/API/AssetResource.php

@@ -29,6 +29,8 @@ class AssetResource extends JsonResource
             'whitelist' => $this->whitelist,
             'latitude' => $this->latitude,
             'longitude' => $this->longitude,
+            'parent_id' => $this->parent_id,
+            'children' => $this->parent_id == 0 ? AssetResource::collection($this->children) : [],
         ];
     }
 }

+ 5 - 1
app/Models/Asset.php

@@ -20,7 +20,7 @@ class Asset extends Model
     protected $fillable = [
         "name", "code", "description", "company_id", "status", "created_by",
         "owner", "address", "group_id", "geo_address_code", "acl",
-        "whitelist", "latitude", "longitude"
+        "whitelist", "latitude", "longitude","parent_id",
     ];
 
     protected static function booted(): void
@@ -36,4 +36,8 @@ class Asset extends Model
             return $query->where('acl', AssetACL::CUSTOM->value)->where('whitelist', 'like', '%' . Auth::id() . '%');
         });
     }
+
+    public function children(){
+        return $this->hasMany(Asset::class ,'parent_id');
+    }
 }

+ 28 - 0
database/migrations/2024_03_04_100338_add_parent_id_to_assets.php

@@ -0,0 +1,28 @@
+<?php
+
+use Illuminate\Database\Migrations\Migration;
+use Illuminate\Database\Schema\Blueprint;
+use Illuminate\Support\Facades\Schema;
+
+return new class extends Migration
+{
+    /**
+     * Run the migrations.
+     */
+    public function up(): void
+    {
+        Schema::table('assets', function (Blueprint $table) {
+            $table->integer('parent_id')->default(0);
+        });
+    }
+
+    /**
+     * Reverse the migrations.
+     */
+    public function down(): void
+    {
+        Schema::table('assets', function (Blueprint $table) {
+            $table->dropColumn('parent_id');
+        });
+    }
+};