0
votes

I have the following models and relations

class Advert extends Model
{
    public function category() {
        return $this->belongsTo('App\Category');
    }
}

class Category extends Model
{

    public function parent() {
        return $this->belongsTo('App\Category', 'category_id','id');
    }

    public function children() {
        return $this->hasMany('App\Category', 'category_id');
    }

    public function adverts() {
        return $this->hasMany('App\Advert');
    }
}

I have table with adverts who belong to a category ... The advert's category can be a subcategory of another category ... Subcategory level is max 4. How can i retrieve all the adverts from all subcategories through the main root category it belongs.

For example

<ul>
<li>Smartphones
  <ul>
      <li>Android
          <ul>
              <li>Samsung</li>
              <li>Huawei</li>
              <li>LG</li>
              <li>Meizu</li>
              <li>Acer</li>
          </ul>
      </li>
      <li>Apple
          <ul>
              <li>iPhone 5</li>
              <li>iPhone 6</li>
              <li>iPhone X</li>
          </ul>
      </li>
  </ul>
</li>
</ul>

How can i get all adverts from all subcategories for example if i click on Smartphones ... Do i have to iterate through each level or there is an easier solution with relations...

Thanks

2
Create a recursive function, that takes the current category as a parameter. In this function, check if this category have any children. Echo the children, and perform a check if they to have children, if so, call the function you just created for those children, from within the loop in the functionOle Haugset
This seems very similar: stackoverflow.com/a/38216669/1744771James Sheils
@JamesSheils this kinda helped me but its not fetching the adverts from the last level of categories ...Nenad Kaevik

2 Answers

0
votes

you can make relations recursive

class Advert extends Model
{
    public function category() {
        return $this->belongsTo('App\Category');
    }
}

class Category extends Model
{

    public function parent() {
        return $this->belongsTo('App\Category', 'category_id','id');
    }

    public function parentRecursive()
    {
        return $this->parent()->with('parentRecursive');
    }



    public function children() {
        return $this->hasMany('App\Category', 'category_id');
    }

    public function childrenRecursive()
    {
        return $this->children()->with('childrenRecursive');

    }

    public function adverts() {
        return $this->hasMany('App\Advert');
    }
}

for getting adverts with recursive results

$adverts = Advert::with('Category')
    ->with('Category.childrenRecursive')->whereNull('Category.parent')->get();
0
votes

Try to use nested sets package. It is awesome and easily do this work.