Laravel Eloquent如何实现分类表自连接查询获取父分类信息
你当前使用的自关联表结构示例如下:
实现方案
1. 定义Eloquent模型
首先创建对应的模型文件app/Models/ProductCategory.php:
<?php namespace App\Models; use Illuminate\Database\Eloquent\Model; use Illuminate\Database\Eloquent\Relations\BelongsTo; class ProductCategory extends Model { // 绑定数据库表 protected $table = 'product_categories'; // 允许批量赋值的字段 protected $fillable = ['name', 'parent']; // 定义父分类关联关系 public function parentCategory(): BelongsTo { return $this->belongsTo(ProductCategory::class, 'parent', 'id'); } }
2. 查询实现
方案一:关联预加载查询(推荐)
符合Eloquent的使用规范,后续扩展更灵活:
$categories = ProductCategory::with('parentCategory') ->orderBy('name', 'asc') ->get(['id', 'name', 'parent']);
Blade视图循环输出示例:
@foreach ($categories as $item) <div> 分类ID:{{ $item->id }} 分类名称:{{ $item->name }} 父分类名称:{{ optional($item->parentCategory)->name ?? '无' }} </div> @endforeach
方案二:自连接查询(和你原生SQL返回结构完全一致)
如果不需要改动原有视图逻辑,直接用查询构造器写自连接即可:
$categories = ProductCategory::from('product_categories as c') ->leftJoin('product_categories as parents', 'parents.id', '=', 'c.parent') ->select('c.id', 'c.name', 'parents.name as Parent Category Name') ->orderBy('c.name', 'asc') ->get();
该查询返回的字段结构和你使用原生DB::select得到的结果完全相同,可直接兼容原有输出逻辑。
内容的提问来源于stack exchange,提问作者stackoverflow account
相关产品推荐
相关产品推荐

