Last active
October 26, 2023 14:27
-
-
Save joaorbrandao/f23c8e4cdf776a2dfe7fd1f75f64f15e to your computer and use it in GitHub Desktop.
Laravel Model Self Reference
This file contains 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; | |
} | |
} |
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?
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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() "