表1:categories: id,name,parent_id
id name parent_id
1 Vehicle null
2 Car 1
3 Sedan 2
Vehicle > Car > Sedan
表2:features: id, name
id name
1 type
2 cylinder
3 color
4 weight
表3:category_feature: category_id, feature_id
category_id feature_id
1 1
1 2
2 3
3 4
我可以按父(类别)获得所有功能。
例如:
类别模型:
public function features()
{
return $this->belongsToMany(Feature::class);
}
并且:
$category = Category::find(1);
$features = $category->features()->get();
如何按子类别分类 孩子的所有特征和父亲的类别的特征?
类似这样的东西:
$category = Category::find(3);
$features = $category->parent_features()->get();
我希望它返回这些:类型,圆柱体,颜色,重量
答案 0 :(得分:0)
在类别模型上:
public function parent(){
return $this->belongsTo(\App\Category::class);
}
然后您可以一次性加载它:
$category = Category::with(['features', 'parent' => function($query){
$query->with('features');
}])->find(3);
然后您可以使用父母的功能:
$features = $category->parent->features;
或原始汽车的功能:
$originalFeatures = $category->features;