# BaseModel系统字段配置使用指南 ## 概述 BaseModel提供了灵活的系统字段自动维护功能,允许开发者根据不同表的需求选择性地启用或关闭系统字段的自动维护。 ## 配置选项 ### 1. `$enableSystemFields` 控制是否自动维护系统字段,默认为 `false`。 **维护的字段包括:** - `tenant_id` - 租户ID - `creator` - 创建者 - `create_time` - 创建时间 - `updater` - 更新者 - `update_time` - 更新时间 - `deleted` - 删除标识 ### 2. `$enableTenantScope` 控制是否启用租户隔离查询,默认为 `false`。 **功能:** - 自动在查询中添加 `tenant_id` 过滤条件 - 确保用户只能访问自己租户的数据 ## 使用示例 ### 主要业务表(推荐启用) ```php get(); // 只查询已删除的记录 $deletedSchools = School::onlyTrashed()->get(); ``` ### Q2: 如何跨租户查询? ```php // 跨租户查询 $allSchools = School::withoutGlobalScope('tenant')->get(); ``` ### Q3: 如何为现有表添加系统字段? ```php // 创建迁移文件 php artisan make:migration add_system_fields_to_schools_table // 在迁移文件中添加字段 public function up() { Schema::table('schools', function (Blueprint $table) { $table->integer('tenant_id')->default(0)->comment('租户ID'); $table->integer('creator')->default(0)->comment('创建者'); $table->timestamp('create_time')->useCurrent()->comment('创建时间'); $table->integer('updater')->default(0)->comment('更新者'); $table->timestamp('update_time')->useCurrent()->on('update')->comment('更新时间'); $table->tinyInteger('deleted')->default(0)->comment('删除标识'); // 添加索引 $table->index('tenant_id'); $table->index('deleted'); }); } ``` ### Q4: 如何自定义系统字段的值? ```php // 在模型中重写方法 public function setCreateFields(): void { if (!$this->enableSystemFields) { return; } // 自定义逻辑 $this->creator = auth()->id() ?? 0; $this->create_time = now(); $this->tenant_id = $this->getCustomTenantId(); $this->deleted = 0; } ``` ## 总结 通过合理配置BaseModel的系统字段维护功能,可以: 1. **提高开发效率** - 自动维护常用的系统字段 2. **增强数据安全** - 租户隔离确保数据安全 3. **简化代码逻辑** - 减少重复的字段维护代码 4. **提高灵活性** - 根据表的特点选择性启用功能 建议在项目开始时就规划好各个表的配置策略,确保系统的一致性和可维护性。