I have navbar with unknown levels of industries which can have child industries and I want to write recursive relationship to get the top one and show it as Category. I tried this:
public function category()
{
if($this->parent_id == 0){
return $this;
} else {
$this->parent_industry->category();
}
}
But I keep getting LogicException: Relationship method must return an object of type Illuminate\Database\Eloquent\Relations\Relation
How to write recursive relationship and return $this?
Try this relations:
public function children()
{
return $this->hasMany('App\MenuItem', 'parent_id');
}
public function parent()
{
return $this->belongsTo('App\MenuItem', 'parent_id');
}
public function getRoot()
{
$cur = $this;
while ($cur->parent) {
$cur = $cur->parent;
}
return $cur;
}
Hi you can do this in an easy rather than using while
public function children()
{
return $this->hasMany('App\MenuItem', 'parent_id');
}
public function parent()
{
return $this->belongsTo('App\MenuItem', 'parent_id');
}
public function root()
{
if ($this->parent)
return $this->parent->root();
return $this;
}
Using recursion it is much simpler.
Hope this helps.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With