In Laravel, I have a table which contains id, parent_id, slug (Self-referring),
When I have an ID, I need to get all its ancestors in a format like this (Separated by "/").
level1/level2/level3
But in an efficient way without a package like "laravel-nestedset ".
I have implemented it like this.
public function parent()
{
return $this->belongsTo('Collection', 'parent_id');
}
public function getParentsAttribute()
{
$parents = collect([]);
$parent = $this->parent;
while(!is_null($parent)) {
$parents->push($parent);
$parent = $parent->parent;
}
return $parents;
}
Any other way to do it efficiently and separated by "/" ?
via Chebli Mohamed
Aucun commentaire:
Enregistrer un commentaire