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...
section Properties
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!?
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);
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();
:)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.