-
-
Save joaorbrandao/f23c8e4cdf776a2dfe7fd1f75f64f15e to your computer and use it in GitHub Desktop.
<?php | |
namespace App\Traits; | |
trait SelfReferenceTrait | |
{ | |
protected $parentColumn = 'parent_id'; | |
public function parent() | |
{ | |
return $this->belongsTo(static::class); | |
} | |
public function children() | |
{ | |
return $this->hasMany(static::class, $this->parentColumn); | |
} | |
public function allChildren() | |
{ | |
return $this->children()->with('allChildren'); | |
} | |
public function root() | |
{ | |
return $this->parent | |
? $this->parent->root() | |
: $this; | |
} | |
} | |
Oi João, how would the parent() look like if we allow multiple parents? Would it just be a change to belongsToMany?
I think the root() method wouldn't work if parent() relation has changed to a belongsToMany.
Hi , i tried to use this trait , the parent and the children functions work perfectly , but the root function gives me an error
"Call to undefined method App\Models\Category::addEagerConstraints() "
Hi , i tried to use this trait , the parent and the children functions work perfectly , but the root function gives me an error
"Call to undefined method App\Models\Category::addEagerConstraints() "
You need to call it like this $model->root() not like $model->with('root');
Thank you sir, it works now, but only for one model instance .
Do you have any idea on how can i call it for all the model instances returned?
Oi João, how would the parent() look like if we allow multiple parents? Would it just be a change to belongsToMany?