简体   繁体   English

Laravel多级SELECT子级

[英]Laravel 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). 一个section可以有多个小节,而那些小节可以有多个小节,依此类推,以此类推(您知道了)。

what am trying to do is load some ads let's say (10) out of all sections that are descendant of a section, so... 我们要做的是加载一部分广告的所有部分中的(10)个广告,因此...

section Properties itself can have ads , and Rent by itself can has it's own ads, and it goes to it's descendant sections ... Properties部分本身可以拥有广告,而“ Rent本身可以拥有自己的广告,然后转到其子孙部分...

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 . 它会加载所有sub-sections的所有sub-sections ,但不会加载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);

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();

:) :)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM