Search code examples
phpormlaravellaravel-3

Laravel ORM Model Hierarchy?


I want to create a One-to-Many relationship for one model.

Exactly I want to build a hierarchy of categories.

For that I have a migration script that creates a foreign key / column category_id.

In the database this is easy. Create one category "Cars". Create another category "Audi" with parent id linked to id of "Cars".

But when I create a function in the ORM model like this:

public function category() {
    return $this->belongs_to('Category');
}

Then I create an infinite loop.

What am I doing wrong? Maybe this is just not possible?

Thank your for your suggestions!


Solution

  • Now I got this working with the ORM functionality. This works fine, my view can handle with it!

    public function children() {
        return $this->has_many('Category','category_id');
    }
    
    public function parent()
    {
        return $this->belongs_to('Category','category_id');
    }