You can do that and you can also use a package like Baum if you need more features and deeper nesting.
Dec 31, 2016
3
Level 1
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 ?
Level 50
3 likes
Please or to participate in this conversation.