Eluknow's avatar

One-to-many relationship with a same model ?

Hi everyone ! I wonder if it was possible to do a one-to-many relationship with a same model.. In fact, I've a model called "Category". And i'd like that a category can have some sub-categories that would come from the same model... I would have something like that :

/*
    |--------------------------------------------------------------------------
    | Relationship Methods
    |--------------------------------------------------------------------------
    */
    
    /**
     * One To Many Relationship Method for accessing the subcategory->category
     * 
     * @return QueryBuilder Object
     */
    public function parent()
    {
        return $this->belongsTo('App\Models\Category', 'parent_id');
    }

    /**
    * One To Many Relationship Method for accessing the parent-category->children-categories
    *
    * @return QueryBuilder Object
     */
    public function children()
    {
        return $this->hasMany('App\Models\Category', 'parent_id');
    }

And I wonder if it was the good way to do what I want... May anyone help me ?

0 likes
3 replies
SaeedPrez's avatar
Level 50

You can do that and you can also use a package like Baum if you need more features and deeper nesting.

3 likes
Eluknow's avatar

Thanks ! I didn't know Baum. But what I want don't need any package I think, it's easy enough. Thank you @SaeedPrez

1 like
SaeedPrez's avatar

@Eluknow Glad I could help ☺

You can also use multiple models with global scopes, for example Category and Subcategory where both use the categories table but the global scopes filters the results based on the parent_id column.

Category::all() // would return all instances where parent_id is null

Subcategory::all() // would return all instances where parent_id is not null

Please or to participate in this conversation.