Home > OS >  Laravel Get releated records grom the same table
Laravel Get releated records grom the same table

Time:07-13

I have table "categories" with following structure: id | parent_id | title

As you see some categories has child categories. And now i would like to get categories with child categories.

Category::childCategories()->get();

And in model categories I wrote this method.

public function childCategories(): HasMany
    {
        return $this->where('parent_id', $this->id);
    }

But I have following error:

Call to undefined method Illuminate\Database\Eloquent\Builder::childCategories()

How should i do it?

Thank you.

CodePudding user response:

Can you please try below code:

public function parentCategory() {
  return $this->belongsToOne(Category::class, 'parent_id');
}

public function childCategories() {
  return $this->hasMany(Category::class, 'parent_id')->orderBy('title', 'asc');
}
  • Related