Php 检索/收集父母关系的最佳方式是什么?
我有一个简单的嵌套分类系统,其中包含一些功能。因此,每个类别都有许多特征,反之亦然 类别Php 检索/收集父母关系的最佳方式是什么?,php,laravel,relationship,Php,Laravel,Relationship,我有一个简单的嵌套分类系统,其中包含一些功能。因此,每个类别都有许多特征,反之亦然 类别 id title parent_id -- ----- --------- 1 car 0 2 suv 1 3 sport 1 4 4x4 2 5 4x2 2 特征 id title -- ----- 1 color 2 dimension 3 ps 类别功能 id category_id f
id title parent_id
-- ----- ---------
1 car 0
2 suv 1
3 sport 1
4 4x4 2
5 4x2 2
特征
id title
-- -----
1 color
2 dimension
3 ps
类别功能
id category_id feature_id
-- ----------- ----------
1 1 1
2 1 2
3 2 3
类别
public function children()
{
return $this->hasMany($this, 'parent_id', 'id')->with('children');
}
public function features()
{
return $this->belongsToMany(Feature::class, 'category_feature', 'category_id', 'feature_id');
}
特征
public function categories()
{
return $this->belongsToMany(Category::class, 'category_feature', 'feature_id', 'category_id');
}
例如:
car
|
suv-------sport
|
4x4-----4x2
在这里,汽车类别是根,具有例如“颜色”和“尺寸”特征,而suv类别具有“ps”特征。当然,这些功能也有变体,但这不是重点
当我调用“4x2”类别时,我想要(急切加载)检索所有祖先特性(级联)。实现这一目标的最佳方法是什么?经过几次尝试后,我意识到解决方案已经存在。以一种简单的方式,我只需要添加一个重复出现的父母关系,因为我已经在儿童关系上使用了。之后,我可以将所有现有的父对象(包括特性关系)加载到根目录。我喜欢它。简单、干净、快速 我的意思是:
public function children()
{
return $this->hasMany($this, 'parent_id', 'id')->with('children');
}
我已经在使用上面的关系,这使得加载所选类别下的所有子级成为可能。它是从自身重复出现的,因为我们在末尾使用了带('children')的渴望加载程序
所以我用同样的方法让父母喜欢:
public function parents()
{
return $this->hasMany($this, 'parent_id', 'id')->with('parents.features');
}
现在,我将能够急切地加载父级直到根。如果不是顶级类别,则在到达顶级类别之前,将始终有一个父类别。不要忘了,如果我想收集所有的功能,我也必须为所有家长加载功能。为此,我只添加了特性和带有('parents.features')的点状代码>。在这一点之后,我当然需要做一些额外的过程来收集所有的特性,但这也很容易
此外,如果模型非常拥挤,我甚至可以通过只选择所需的列来稀疏一些列。有趣,简单