Skip to content

Instantly share code, notes, and snippets.

@ThisIsntMyId
Created July 4, 2021 18:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ThisIsntMyId/7ad65775ef959e470caaed8877c82a7e to your computer and use it in GitHub Desktop.
Save ThisIsntMyId/7ad65775ef959e470caaed8877c82a7e to your computer and use it in GitHub Desktop.
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;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment