簡體   English   中英

Laravel多級SELECT子級

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM