Skip to content

Instantly share code, notes, and snippets.

@technoknol
Last active January 28, 2023 07:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save technoknol/68bd2bcaca8efa7c8e7c9ed533414ce3 to your computer and use it in GitHub Desktop.
Save technoknol/68bd2bcaca8efa7c8e7c9ed533414ce3 to your computer and use it in GitHub Desktop.
Recursive to self model (Recursive Children and Recursive Parents) - Laravel
<?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