Laravel 9中如何获取品牌关联的商品分类并输出API数据
Laravel 9 实现指定品牌关联分类的API方案
一、优化模型关联(可选但更规范)
首先修正模型中的关联命名,确保语义准确:
- Product.php 中多对多关联改为复数形式:
public function categories() { return $this->belongsToMany(Category::class, 'product_categories'); }
- Brand.php 添加直接关联分类的方法(数据库层面去重,避免重复分类):
public function categories() { return $this->belongsToMany(Category::class, 'products', 'brand_id', 'id') ->join('product_categories', 'products.id', '=', 'product_categories.product_id') ->select('categories.*') ->distinct(); }
二、实现API控制器
创建或修改 BrandController.php,编写获取品牌分类的逻辑,支持返回扁平结构或树形层级结构:
<?php namespace App\Http\Controllers; use App\Models\Brand; use App\Models\Category; use Illuminate\Http\Request; class BrandController extends Controller { // 方式1:使用模型关联获取分类 public function getCategoriesViaRelation($id) { $brand = Brand::with('categories')->findOrFail($id); // 如需树形结构,调用辅助方法转换 $treeCategories = $this->buildCategoryTree($brand->categories); return response()->json([ 'success' => true, 'data' => $treeCategories ]); } // 方式2:直接通过分类模型查询(无需修改Brand模型) public function getCategoriesViaQuery($id) { $categories = Category::whereHas('products', function ($query) use ($id) { $query->where('brand_id', $id); })->distinct()->get(); $treeCategories = $this->buildCategoryTree($categories); return response()->json([ 'success' => true, 'data' => $treeCategories ]); } // 辅助方法:将扁平分类转为树形结构 private function buildCategoryTree($categories) { $categoryMap = []; $tree = []; foreach ($categories as $category) { $categoryMap[$category->id] = $category; $category->children = collect(); } foreach ($categories as $category) { if ($category->parent_id && isset($categoryMap[$category->parent_id])) { $categoryMap[$category->parent_id]->children->push($category); } else { $tree[] = $category; } } return $tree; } }
三、配置API路由
在 routes/api.php 中添加路由:
// 使用模型关联的接口 Route::get('/brands/{id}/categories', [\App\Http\Controllers\BrandController::class, 'getCategoriesViaRelation']); // 或使用直接查询的接口(二选一即可) // Route::get('/brands/{id}/categories', [\App\Http\Controllers\BrandController::class, 'getCategoriesViaQuery']);
四、注意事项
- 性能优化:为
products.brand_id、product_categories.product_id、product_categories.category_id添加数据库索引,提升关联查询效率。 - 分页支持:如果分类数量较多,可在查询时添加
->paginate(10)替换->get(),实现分页返回。 - 结构选择:前端需要层级展示时用树形结构,仅需列表时直接返回扁平的
$categories即可。
内容的提问来源于stack exchange,提问作者MJerbi
相关产品推荐
相关产品推荐

