【发布时间】:2023-03-13 14:03:02
【问题描述】:
这是我的产品表:
- 身份证
- 姓名
- category_id
这是我的类别表:
- 身份证
- 标题
- parent_id
我想获取属于指定类别及其子类别的所有产品(按类别 ID)。
Products 表中的category_id 总是引用一个子类别
我尝试了 HasManyThrough,但无法对检索到的产品进行分页。
【问题讨论】:
-
请告诉我们您到现在为止尝试过的查询。
这是我的产品表:
这是我的类别表:
我想获取属于指定类别及其子类别的所有产品(按类别 ID)。
Products 表中的category_id 总是引用一个子类别
我尝试了 HasManyThrough,但无法对检索到的产品进行分页。
【问题讨论】:
这适用于一级子类别:
Product::whereHas('category', function($q) use($categoryId) {
$q->where('category', $categoryId)
->orWhere('parent_id', $categoryId);
})
->get();
category 是 belongsTo 关系。
【讨论】:
首先获取所有类别并遍历它并获取属于该类别的所有产品,您可以限制每个类别的产品数量,例如 10 个。
之后,如果用于前端,则使用ajax,对于API的直接传递偏移量,给它特定类别的特定数量的偏移量。
希望这会有所帮助。
【讨论】:
//In Products Controller
$products= DB::table('products')->select('products.*')
->join('categories', 'categories.id' ,'=', 'products.category_id')
->get();
//or
//here is using model name also
use App\Products;
$products= Products::select('products.*')
->join('categories', 'categories.id' ,'=', 'products.category_id')
->get();
【讨论】:
首先在Category模型中写下这些方法:
public function children(){
return $this->hasMany(Category::class, 'parent_id');
}
public function parent(){
return $this->belongsTo(Category::class, 'parent_id');
}
public function products(){
return $this->hasMany(Product::class, 'category_id');
}
在Product 模特:
public function category(){
return $this->belongsTo(Category::class, 'category_id');
}
现在在控制器中:
$res = Category::with([
'products',
'children.products'
])->find($your_category_id);
使用dd($res) 并查看结果。希望有效
【讨论】: