[英]Laravel Multi-Level SELECT on childern
我有两个表:
Table Section
id name section_id
1 Properties 0
2 Rent 1
3 Sale 2
4 Houses 2
5 Lands 2
和
Table Ads
id section_id ....
果胶模型
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);
}
}
广告模型
class Ad extends Model
{
public function Section()
{
return $this->belongsTo(Section::class);
}
}
一个section
可以有多个小节,而那些小节可以有多个小节,依此类推,以此类推(您知道了)。
我们要做的是加载一部分广告的所有部分中的(10)个广告,因此...
“ Properties
部分本身可以拥有广告,而“ Rent
本身可以拥有自己的广告,然后转到其子孙部分...
我试图做的是使用预加载,如下所示:
$probs = Section::where('name', 'Properties')->first()->SubSections()->with('SubSections','Ads')->get();
它会加载所有sub-sections
的所有sub-sections
,但不会加载Ads
。
我想念这里!!
这是您可以获得一切的方式
$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);
根据这个 ,你可以这样做?
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();
:)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.