2021年1月17日星期日

What is the best way to retrieve/gather (eager load) relations of parents?

I have a simple nested category system with features. So each category has many features and vice versa.

categories

id   title   parent_id  --   -----   ---------  1    car     0  2    suv     1  3    sport   1  4    4x4     2  5    4x2     2  

features

id   title  --   -----  1    color  2    dimension  3    ps  

category_feature

id  category_id  feature_id  --  -----------  ----------  1   1            1  2   1            2  3   2            3  

category

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');  }  

feature

public function categories()  {      return $this->belongsToMany(Category::class, 'category_feature', 'feature_id', 'category_id');  }  

for example:

             car                |          suv-------sport           |      4x4-----4x2  

Here the car category is the root and has for example "color" and "dimension" features and the suv category has "ps" feature. Of course these features have variants but that is not the point here.

What I want is to (eager load) retreive all the ancestor features (cascade) when I call the "4x2" category. What would the best way to achive this?

https://stackoverflow.com/questions/65760462/what-is-the-best-way-to-retrieve-gather-eager-load-relations-of-parents January 17, 2021 at 08:16PM

没有评论:

发表评论