pion/laravel-support-collection

Laravel 集合的支持类

v1.1.2 2022-02-11 14:01 UTC

This package is auto-updated.

Last update: 2024-09-11 20:52:23 UTC


README

用于改进集合的类混合。

安装

composer require pion/laravel-support-collection

NestedObjectCollection

根据父属性和id属性,从扁平集合创建嵌套集合到子嵌套集合。

期望值是 对象,它将子项插入到所需的属性中。

所有子项都存储在对象的子属性中。可以为空。

您可以在NestedObjectCollection对象上调用所有集合方法,所有方法调用都传递到集合中

构造函数

根据父属性分组项目,并从树的顶部(null属性或不同值)循环,并将子项添加到对象中。

参数

  • 集合 $items

  • 字符串 $parentProperty 获取父id的属性名

  • 字符串 $idProperty 获取id值的属性名

  • 字符串 $rootIndexKeyOnGroup 获取根元素的索引键。当父属性值返回null时,它将是空字符串。

  • 字符串 $propertyForChildren 存储子项的属性名

    public function __construct(Collection $items, $parentProperty = "parent_id", $idProperty = "id", $rootIndexKeyOnGroup = "", $propertyForChildren = "childs")

Eloquent 使用

建议在Eloquent模型中设置属性以防止将子项创建到属性中。对于默认属性名,您可以使用 ChildsCollectionTrait。这为您的Eloquent模型提供了一个公共的 $childs 属性

示例

$object1 = new stdClass();
$object1->id = 1;

// this is the root!
$object1->parent_id = null;

$object2 = new stdClass();

$object2->id = 2;
$object2->parent_id = 2;


$object3 = new stdClass();

$object3->id = 3;
$object3->parent_id = 1;

$example = new \Pion\Support\Collection\NestedObjectCollection(new \Illuminate\Support\Collection([
    $object1, $object2, $object3
]));

$collection = $example->getCollection();

此示例将创建一个包含单个项目($object1)的集合。这些对象将具有一个新属性$childs,它包含一个包含单个项目$object2的集合,该集合再次具有属性$childs,包含单个项目$object3

GroupedCollection

启用快速构建分组集合的方法。只需向集合中添加具有给定组键和值的项。可选地,您还可以提供值的键。

public function add($groupKey, $value, $key = null)

示例

集合的使用与标准集合相同。

$groupedCollection = new GroupedCollection();
$groupedCollection->add("1", "test 1");
$groupedCollection->add("1", "test 2");
$groupedCollection->add("1", "test 3");
$groupedCollection->add("2", "test 2-1");
$groupedCollection->add("2", "test 2-2");

这将导致一个包含集合对象的项集合。如果您将集合导出为数组,则将按预期分组数组。

var_dump($groupedCollection->toArray());

array(2) {
  [1] =>
  array(3) {
    [0] =>
    string(6) "test 1"
    [1] =>
    string(6) "test 2"
    [2] =>
    string(6) "test 3"
  }
  [2] =>
  array(2) {
    [0] =>
    string(8) "test 2-1"
    [1] =>
    string(8) "test 2-2"
  }
}