在电商类 Laravel 项目中,商品通常和分类存在多对多或者一对多的关联关系,当需要根据某个父分类查询其下所有子分类的商品时,whereIn 是常用的查询手段,但很多开发者会因为关联模型使用不当或者查询逻辑错误导致结果不符合预期。

前置准备:定义关联模型
首先我们需要定义分类和商品的模型关联关系,假设分类表有 id、parent_id、name 字段,商品表有 id、name、price 字段,分类和商品是多对多关联关系,中间表为 category_product,包含 category_id 和 product_id 字段。
分类模型 Category.php
<?php
namespace AppModels;
use IlluminateDatabaseEloquentModel;
class Category extends Model
{
// 获取当前分类的子分类
public function children()
{
return $this->hasMany(Category::class, 'parent_id', 'id');
}
// 获取当前分类关联的商品
public function products()
{
return $this->belongsToMany(Product::class, 'category_product', 'category_id', 'product_id');
}
}
商品模型 Product.php
<?php
namespace AppModels;
use IlluminateDatabaseEloquentModel;
class Product extends Model
{
// 获取商品关联的分类
public function categories()
{
return $this->belongsToMany(Category::class, 'category_product', 'product_id', 'category_id');
}
}
常见错误用法示例
很多开发者会先获取父分类下的所有子分类 ID,然后直接用 whereIn 查询商品,示例如下:
<?php
$parentId = 1;
// 获取父分类下的所有子分类ID
$childCategoryIds = Category::where('parent_id', $parentId)->pluck('id')->toArray();
// 直接查询商品
$products = Product::whereIn('id', function ($query) use ($childCategoryIds) {
$query->select('product_id')
->from('category_product')
->whereIn('category_id', $childCategoryIds);
})->get();
这种写法的问题在于如果子分类存在多级嵌套,比如子分类下还有子分类,上述代码只能获取到一级子分类的商品,无法覆盖所有层级的子分类。
正确实现方案
方案一:递归获取所有子分类 ID 后使用 whereIn
我们可以先写一个递归方法获取某个父分类下所有层级的子分类 ID,再结合 whereIn 查询商品。
<?php
// 递归获取所有子分类ID
function getAllChildCategoryIds($parentId, &$ids = [])
{
$childIds = Category::where('parent_id', $parentId)->pluck('id')->toArray();
foreach ($childIds as $childId) {
$ids[] = $childId;
getAllChildCategoryIds($childId, $ids);
}
return $ids;
}
$parentId = 1;
// 获取所有层级的子分类ID
$allChildCategoryIds = getAllChildCategoryIds($parentId);
// 去重避免重复ID
$allChildCategoryIds = array_unique($allChildCategoryIds);
// 查询关联商品
$products = Product::whereHas('categories', function ($query) use ($allChildCategoryIds) {
$query->whereIn('category_id', $allChildCategoryIds);
})->get();
方案二:使用闭包结合 whereIn 实现子查询
如果不想提前获取所有子分类 ID,可以使用闭包子查询的方式,直接在查询中完成子分类的筛选。
<?php
$parentId = 1;
$products = Product::whereHas('categories', function ($query) use ($parentId) {
$query->whereIn('category_id', function ($subQuery) use ($parentId) {
// 这里可以根据需要添加多级子分类的查询逻辑,比如使用递归闭包
$subQuery->select('id')
->from('categories')
->where('parent_id', $parentId);
});
})->get();
方案三:使用 with 预加载后筛选
如果需要同时获取商品的分类信息,可以结合 with 预加载和 whereIn 进行筛选。
<?php
$parentId = 1;
$childCategoryIds = Category::where('parent_id', $parentId)->pluck('id')->toArray();
$products = Product::with(['categories' => function ($query) use ($childCategoryIds) {
$query->whereIn('category_id', $childCategoryIds);
}])->whereHas('categories', function ($query) use ($childCategoryIds) {
$query->whereIn('category_id', $childCategoryIds);
})->get();
注意事项
- 使用 whereIn 时如果传入的 ID 数组为空,需要提前做判断,避免出现 SQL 语法错误。
- 如果子分类层级很深,递归获取 ID 的方式可能会有性能问题,可以考虑给分类表添加 path 字段存储分类路径,方便快速查询所有子分类。
- whereHas 方法会自动生成 exists 子查询,比手动写 whereIn 子查询的可读性更好,推荐优先使用。
| 方案 | 优点 | 缺点 |
|---|---|---|
| 递归获取子分类ID+whereIn | 逻辑清晰,易于理解 | 多级子分类时递归可能有性能开销 |
| 闭包子查询+whereIn | 不需要提前获取ID,查询一次性完成 | 复杂子查询可读性较差 |
| with预加载+whereIn | 可以同时获取关联分类数据,减少查询次数 | 查询逻辑相对复杂 |