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

MixedCoder's avatar

Multi-Level SELECT on childern

I have two tables:

Table Section
id name section_id
1 Properties 0
2 Rent       1
3 Sale       2
4 Houses     2
5 Lands      2

and

Table Ads
id section_id ....

Sectoin Model

 class Section extends Model
    {
        public function Ads()
        {
            return $this->hasMany(Ad::class);
        }
    
        public function SubSections()
        {
            return $this->hasMany(Section::class);
        }
    
        public function Parent()
        {
            return $this->belongsTo(Section::class);
        }
    }

Ad Model

class Ad extends Model
{
 
    public function Section()
    {
        return $this->belongsTo(Section::class);
    }


}

a section can have sub-sections and those sub-sections can have sub-sections , and so on and so forth, (you got the idea).

what am trying to do is load some ads let's say (10) out of all sections that are descendant of a section, so...

sectionProperties itself can have ads , and Rent by itself can has it's own ads, and it goes to it's descendant sections ...

what I have tried to do is use eager loading as follow:

$probs = Section::where('name', 'Properties')->first()->SubSections()->with('SubSections','Ads')->get();

it loads all the sub-sections of sub-sections , but not the Ads.

what I miss here!?

0 likes
0 replies

Please or to participate in this conversation.