Last active
September 13, 2024 19:02
-
-
Save joaorbrandao/f23c8e4cdf776a2dfe7fd1f75f64f15e 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; | |
| } | |
| } | |
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?
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
You need to call it like this $model->root() not like $model->with('root');