php Laravel:如何扁平化一个多维的渴望加载的集合

zysjyyx4  于 5个月前  发布在  PHP
关注(0)|答案(1)|浏览(38)

我有一个集合,里面有急切加载的嵌套后代(区域模型):

Illuminate\Database\Eloquent\Collection {#1649 ▼
  #items: array:1 [▼
    0 => App\Models\Region {#1650 ▼
      ...
      #relations: array:1 [▼
        "descendants" => Illuminate\Database\Eloquent\Collection {#1646 ▼
          #items: array:2 [▼
            0 => App\Models\Region {#1660 ▶}
              …
              #relations: array:1 [▼
                "descendants" => Illuminate\Database\Eloquent\Collection {#1657 ▼
                  #items: array:2 [▼
                    0 => App\Models\Region {#1672 ▶}
                    1 => App\Models\Region {#1671 ▶}
                  ]
            1 => App\Models\Region {#1659 ▶}
etc …

字符串
我想将整个集合扁平化为同一个类的一个集合,以这种方式,新集合中的顺序将是这样的:

Illuminate\Database\Eloquent\Collection {#1676 ▼
  #items: array:10 [▼
    0 => App\Models\Region {#1650 ▶}    (parent)
    1 => App\Models\Region {#1660 ▶}    (child 1)
    2 => App\Models\Region {#1672 ▶}    (grandchild 1)
    3 => App\Models\Region {#1671 ▶}    (grandchild 2)
    4 => App\Models\Region {#1659 ▶}    (child 2)
etc …


我需要它是一个雄辩的模型集合,而不是数组集合。
先谢谢你了!

6jygbczu

6jygbczu1#

定义一个递归函数来扁平化集合。

use Illuminate\Database\Eloquent\Collection;

class RegionController
{
    public function flattenCollection(Collection $collection)
    {
        $flattenedCollection = new Collection();

        foreach ($collection as $region) {
            $flattenedCollection->push($region);

            if ($region->relationLoaded('descendants')) {
                $descendants = $this->flattenCollection($region->descendants);
                $flattenedCollection = $flattenedCollection->merge($descendants);
            }
        }

        return $flattenedCollection;
    }
}

字符串
然后,使用该函数进行展平。

$originalCollection = // your original collection with eager-loaded relationships;

$regionController = new RegionController();
$flattenedCollection = $regionController->flattenCollection($originalCollection);

相关问题