You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Laravel 9中如何获取品牌关联的商品分类并输出API数据

Laravel 9 实现指定品牌关联分类的API方案

一、优化模型关联(可选但更规范)

首先修正模型中的关联命名,确保语义准确:

  1. Product.php 中多对多关联改为复数形式:
public function categories()
{
    return $this->belongsToMany(Category::class, 'product_categories');
}
  1. 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.08 13:35:26