Laravel Multi-Level SELECT on childern

305 views Asked by At

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!?

a screenshot of the tables

1

There are 1 answers

6
prateekkathal On

Here is how you can get everything

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

$sectionAds = $section->Ads;

$subSectionAds = $section->SubSections->filter(function($section) {
  return $section->ads->count() ? $section->ads : false;
})->flatten();

$allAds = $sectionAds->merge($subSectionAds);

UPDATE

According to this, you can do something like...

public function SubSections()
{
  return $this->hasMany(Section::class);
}

public function AllSubSections($section == null)
{
  return $this->SubSections()->with('AllSubSections');
}

$section = Section::with('AllSubSections')->where('name', 'Properties')->get();

$subSections = $section->AllSubSections->flatten();

$subSectionsIds = $subSections->pluck('id')->toArray();

Ads::whereIn('section_id', $subSectionsIds)->get();

:)