Created
August 29, 2018 10:26
-
-
Save taulutwashi/d1e97eca24f76b231dbb98f4370de913 to your computer and use it in GitHub Desktop.
laravel parent child in same table
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
class ProjectTree extends Model { | |
//each category might have one parent | |
public function parent() { | |
return $this->belongsToOne(static::class, 'parent_id'); | |
} | |
//each category might have multiple children | |
public function children() { | |
return $this->hasMany(static::class, 'parent_id')->orderBy('name', 'asc'); | |
} | |
} | |
$ProjectTree = ProjectTree::where('id',$id)->with([ | |
'children'=>function($query){ | |
$query->with([ | |
'children'=>function($query){ | |
$query->with(['children'=> function($query){ | |
$query->with('children'); | |
}]); | |
}]); | |
}])->select(['id'])->get(); | |
<ul> | |
@foreach ($categories as $parent) | |
<li>{{ $parent->cat_name }} | |
@if ($parent->children->count()) | |
<ul> | |
@foreach ($parent->children as $child) | |
<li>{{ $child->cat_name }}</li> | |
@endforeach | |
</ul> | |
@endif | |
</li> | |
@endforeach | |
</ul> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment