本文介绍在 laravel 中如何基于同一张数据表和同一个 eloquent 模型(如 `category`),通过 `parent_category` 字段和 `category_type` 字段协同作用,灵活定义并查询不同层级、不同类型之间的父子级一对多关系。
在实际业务中,分类体系常呈现多层嵌套结构(如“主类目 → 上级类目 → 次级类目 → 子次级类目”),但出于数据一致性与维护性考虑,往往将所有类型统一存于一张 categories 表中,并通过 category_type 区分角色,用 parent_category 指向其逻辑父级。此时,虽仅有一个 Category 模型,仍可通过 Eloquent 的关联方法精准建模各类关系。
首先,在 app/Models/Category.php 中定义通用的双向关联:
use Illuminate\Database\Eloquent\Model;
class Category extends Model
{
use \Illuminate\Database\Eloquent\Factories\HasFactory;
protected $fillable = [
'name', 'short_name', 'description', 'picture',
'category_type', 'parent_category'
];
// 当前分类的父级分类(belo
ngsTo:一个分类属于一个父分类)
public function parentCategory()
{
return $this->belongsTo(Category::class, 'parent_category', 'id');
}
// 当前分类的所有子分类(hasMany:一个分类可拥有多个子分类)
public function childCategories()
{
return $this->hasMany(Category::class, 'parent_category', 'id');
}
}? 关键说明:belongsTo() 使用外键 parent_category 关联到目标表的主键 id;hasMany() 则以当前模型的 id 为“父键”,匹配子记录的 parent_category 字段——二者共同构成树形结构的基础骨架。
若需进一步约束关联结果的 category_type(例如:只获取 category_type = 2 的“上级类目”),可定义带条件的关联方法:
// 仅获取 category_type = 'superior' 的子分类
public function superiorChildCategories()
{
return $this->hasMany(Category::class, 'parent_category', 'id')
->where('category_type', 2); // 或使用字符串 'superior'(需确保数据库值一致)
}
// 获取所有 secondary 类型子分类(category_type = 3)
public function secondaryChildCategories()
{
return $this->hasMany(Category::class, 'parent_category', 'id')
->where('category_type', 3);
}
// 获取其父级且必须是 main 类型(category_type = 1)
public function mainParentCategory()
{
return $this->belongsTo(Category::class, 'parent_category', 'id')
->where('category_type', 1);
}✅ 这些方法返回的是 HasMany / BelongsTo 实例,支持链式调用(如 ->withTrashed())、->get()、->count() 等,且自动应用 WHERE 条件,无需手动 where()。
// 查找首个主类目,并获取其全部上级类目(category_type = 2)
$mainCat = Category::where('category_type', 1)->first();
$superiors = $mainCat->superiorChildCategories()->get(); // 集合,可能为空
// 查找某个次级类目,获取其所属的上级类目(注意:此处 parentCategory 是通用关联)
$secondary = Category::where('category_type', 3)->first();
$superiorParent = $secondary->parentCategory()->where('category_type', 2)->first();
// 推荐写法:直接使用类型限定的关联(更语义化、更安全)
$secondary->mainParentCategory; // 自动过滤 parent 必须是 type=1class CategoryType
{
const MAIN = 1;
const SUPERIOR = 2;
const SECONDARY = 3;
const SUB_SECONDARY = 4;
}并在关联方法中使用 CategoryType::SUPERIOR 提升可读性与可维护性。
$categories = Category::where('category_type', 1)
->with('superiorChildCategories', 'superiorChildCategories.secondaryChildCategories')
->get();通过上述方式,你无需拆分模型或表,即可在单一 Category 模型内清晰表达、安全查询多类型间的层次化一对多关系,兼顾灵活性与工程严谨性。