使用forget后,收集方法值不重置数组键

I have a nested array of objects inside an array of objects.

Pages hasMany sections

I am trying to unset the nested sections and reset their array keys but to no avail.

foreach ($pages as $pageKey => &$page) {
    foreach ($page->sections as $sectionKey => $section) {

        // Remove sections with no questions 
        if ($section->questions->count() < 1) {
            $page->sections->forget($sectionKey);
        }
    }

    $page->sections = $page->sections->values()->all();
}

However, the section keys are not being reset.

enter image description here

What (I assume) you are trying to do is get all the Pages with Sections that has at least Comments. In order to accomplish this you could do this in one query:

$pages = Pages::with(['sections' => function ($query) {
                    $query->has('comments');
                }])
               ->get();

With this, you are eager loading the Sections related the every Page but just the ones that has at least one Comment linked to them.


You can check the documentation related to this topics: