Last active
January 28, 2023 07:21
-
-
Save technoknol/68bd2bcaca8efa7c8e7c9ed533414ce3 to your computer and use it in GitHub Desktop.
Recursive to self model (Recursive Children and Recursive Parents) - Laravel
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 | |
/** | |
* @property float $wallet | |
* @property string $name | |
*/ | |
class User extends Authenticatable | |
{ | |
/** | |
* @return BelongsTo | |
*/ | |
public function parent(): BelongsTo | |
{ | |
return $this->belongsTo(self::class, 'parent_id'); | |
} | |
/** | |
* @return BelongsTo | |
*/ | |
public function parentRecursive(): BelongsTo | |
{ | |
return $this->parent()->with('parentRecursive'); | |
} | |
/** | |
* Get current user's all recursive parents in a collection. | |
*/ | |
public function parentRecursiveFlatten() | |
{ | |
$result = collect(); | |
$item = $this->parentRecursive; | |
if ($item instanceof User) { | |
$result->push($item); | |
$result = $result->merge($item->parentRecursiveFlatten()); | |
} | |
return $result; | |
} | |
/** | |
* @return HasMany | |
*/ | |
public function children(): HasMany | |
{ | |
return $this->hasMany(self::class, 'parent_id'); | |
} | |
/** | |
* @return HasMany | |
*/ | |
public function childrenRecursive(): HasMany | |
{ | |
return $this->children()->with('childrenRecursive'); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment