如何获得类别编辑laravel的子孙的id

I would like to get all the products that fall under a certain category. I have a table of categories that can have up to 3 levels.

->grandparent category
------>Parent category
-------------> Child category

I have a table of products that can fall under any one of these categories (category_id field). If I select a grandparent category I would like to be able to fetch all products such that:

  • The product category_id matches the grandparent category
  • The product category_id field matches a parent category that is a child of the grandparent category.
  • The product category_id field matches a child category that is a child of a parent category that is a child of the grandparent category.

I have the following code:

$category = Category::select('id')
    ->where('parent_id', $category->id)
    ->orWhere('id', $category->id)
    ->get();

The results is a list of Id's which I then use to query the product table. The problem with this code is that it only gets me one level down (i.e the grandparent and parents that fall under it).

Any help much appreciated

You can try a "recursion" function:

    <?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class Grandparents extends Model {

  protected $table = 'your table';

  protected $with = [ 'children' ];

  protected $visible = [ 'id', 'children' ];

  public function children() {
    return $this->hasMany( Grandparents::class, 'parent_id', 'id' )->with( 'children' );
  }
}

And then check if the results are ok:

print_r( \App\Models\Grandparents::where( 'id', '=', 1000 )->get()->toArray() );

Regards, Lukas