如何在单个 Laravel 模型中实现多种类型的自关联一对多关系

本文详解如何在 laravel 的单一 `category` 模型中,基于 `category_type` 和 `parent_category` 字段,灵活定义并查询不同层级的自关联一对多关系(如主类目→上级类目、上级类目→次级类目等)。

在单表多类型分类场景中(如 categories 表通过 category_type 区分“主类目”“上级类目”“次级类目”等),虽然物理上只有一张表和一个 Eloquent 模型,但逻辑上存在清晰的层级依赖关系。此时无需拆分模型,而是通过自关联关系(Self-Referencing Relationships) + 条件约束(Query Scopes 或带 where 的关系方法) 实现语义化、可复用的关联定义。

首先,在 app/Models/Category.php 中补充以下关系方法:

use Illuminate\Database\Eloquent\Model;

class Category extends Model
{
    use HasFactory;

    protected $fillable = [
        'name', 'short_name', 'description', 'picture',
        'category_type', 'parent_category'
    ];

    // 【核心】反向关系:当前分类所属的父分类(一对一)
    public function parentCategory()
    {
        return $this->belongsTo(Category::class, 'parent_category', 'id');
    }

    // 【核心】正向关系:当前分类下的所有子分类(一对多)
    public function childCategories()
    {
        return $this->hasMany(Category::class, 'parent_category', 'id');
    }

    // 【按类型细化】获取指定类型的子分类(例如:主类目 → 上级类目)
    public function superiorChildCategories()
    {
        return $this->childCategories()->where('category_type', 2); // 2 = Superior Category
    }

    // 同理可扩展其他类型关系
    public function secondaryChildCategories()
    {
        return $this->childCategories()->where('category_type', 3); // 3 = Secondary Category
    }

    public function mainParentCategory()
    {
        return $this->parentCategory()->where('category_type', 1); // 只关联到主类目
    }
}

使用示例:

// 获取首个主类目(category_type = 1)
$main = Category::where('category_type', 1)->first();

// 获取它所有的「上级类目」子项(category_type = 2)
$superiors = $main->superiorChildCategories; // 自动应用 where('category_type', 2)

// 获取某个次级类目的直接父类目(无论父类目类型)
$secondary = Category::where('category_type', 3)->first();
$parent = $secondary->parentCategory; // 返回 Category 实例(如为 Superior 类目)

// 链式查询:查找某主类目下所有「次级子类目」的「次级子子类目」
$grandChildren = $main
    ->secondaryChildCategories()
    ->with(['secondaryChildCategories']) // 预加载二级子项
    ->get();

⚠️ 关键注意事项:

  • 数据库字段 parent_category 必须为 BIGINT(与 id 类型一致),且建议添加外键约束(如 ALTER TABLE categories ADD FOREIGN KEY (parent_category) REFERENCES categories(id) ON DELETE SET NULL;);
  • category_type 值应统一用整数(而非字符串),便于数据库索引与查询性能优化;
  • 若需强制类型安全,可在模型中定义常量或访问器:
    const TYPE_MAIN = 1;
    const TYPE_SUPERIOR = 2;
    const TYPE_SECONDARY = 3;
    const TYPE_SUB_SECONDARY = 4;
  • 关系方法返回的是 Illuminate\Database\Eloquent\Relations\HasMany / BelongsTo 实例,调用时加 () 是定义关系,不加 ()(如 $cat->childCategories)才是触发查询
  • 如需懒加载(Lazy Eager Loading)或避免 N+1,务必配合 with() 使用,例如:Category::with('childCategories')->get()。

通过这种设计,你既能保持模型简洁性,又能精准表达业务中的多层分类语义,同时获得 Laravel ORM 全套查询能力(过滤、排序、预加载、分页等),是处理树形结构与类型化自关联的经典实践方案。