-
-
Save Mutembeijoe/0c83c91f2179bd693c8584144c068115 to your computer and use it in GitHub Desktop.
Laravel Model Self Reference
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| <?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; | |
| } | |
| } | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment