在孩子们的Laravel多级选择

时间:2016-12-28 18:44:17

标签: php laravel laravel-5.3 eager-loading multi-level

我有两张桌子:

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 ....

Sectoin模型

 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

我想念的是什么!?

a screenshot of the tables

1 个答案:

答案 0 :(得分:0)

以下是如何获得所有内容

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

更新

根据this,您可以执行类似......

的操作
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();

:)