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

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 …

我需要它是一个Eloquent 的模型集合,而不是数组的集合.

提前谢谢!

推荐答案

定义将使集合扁平化的递归函数.

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

Php相关问答推荐

在PHP中替换数组中的文本并同时使用其他函数

如何使用属性#[Embedded]嵌入带有规则的对象集合?

PHP如何将ARRAY_MAP与Reset()配合使用

Laravel 10 -扩展现有的artisan命令?

WooCommerce/WordPress:简单的产品属性显示

添加登录:需要app.yaml仍然允许所有拥有Google帐户的人访问

我有一个显示记录的表格,每行在最右边有两个按钮.如何才能以正确的顺序获得表的值?

允许客户定义特定WooCommerce产品的价格

在PHP项目中安装OpenAI PHP SDK时出现问题

未定义的类型';PDF';在Laravel 8

未检测到laravel控制器

如何限制 woocommerce 中相关产品的标题长度

如何判断php中wordpress路径之外的文件夹是否存在?

使用 wp_footer 挂钩添加一些 CSS 不起作用

将产品数量、名称和结帐链接添加到 WooCommerce 添加到购物车消息

simplexml_load_file 和 simplexml_load_string 返回具有不同编码的相同数据

将 WooCommerce 0 销售价格替换为自定义文本,并保留常规价格删除线

PHP 简单 XML Xpath 上移树(带有名称的父级)

使用 PHP 的 OAuth 2.0 MAC

适当的时区处理 Laravel / Carbon