Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

ga46's avatar
Level 1

How to write a query to view all parent of all subcategories

suppose I have 100 sub categories and every subcategory has a parent ( suppose 10 parent categories).

so now I try to get all subcategories in one array and another array gets all subcategories and all parent category in the same query is it possible?

0 likes
8 replies
Sinnbeck's avatar

So you want to get subcategories twice? Or just two collections. 1 with all subcategories and 1 with all categories (based on the first collection) ? How is the relationship? Belongs to I assume? And can you show your current code for getting the data?

ga46's avatar
Level 1

@Sinnbeck

    public function parent()
    {
        return $this->belongsTo(Category::class, 'parent_id', 'id');
    }

  public function children()
    {
        return $this->hasMany(Category::class, 'parent_id');
    }
ga46's avatar
Level 1

@sinnbeck the main point is I have only subcategory access but I want to my all subcategory parent as a list (array ) do you understand my point?

Sinnbeck's avatar

@ga46 Not really. Can you show some code? All the subcategories are on the same level ? And you want to get every single parent all the way to the top, for each subcategory?

ga46's avatar
Level 1

@Sinnbeck

sub-1 ----- parent-1
sub-2-----parent-1
sub-3-----parent-2
sub-4----parent-2

suppose i have access all "sub" ,1,2,3,4 now I want to get all of my sub-category parent, that's mean ---parent-1,parent-2

Sinnbeck's avatar

@ga46 So just one for each?

$subs = Category::with('parent')->where('level', 12)->get();

Please or to participate in this conversation.