melihovv / collection-grouped-by-model
按模型分组集合
1.6.0
2020-03-05 23:05 UTC
Requires
- php: >=7.2
- illuminate/support: ^6.0|^7.0
Requires (Dev)
- phpunit/phpunit: ^8.4|^9.0
README
此包允许轻松地按任何PHP对象(模型、模型数组/集合等)对Laravel集合进行分组,而不仅限于标量(字符串、数字、布尔值)。
安装
通过composer安装
composer require melihovv/collection-grouped-by-model
用法
$posts = Post::all() $postsGroupedByAuthor = (new CollectionGroupedByModel($posts))->groupByModel('author_id', 'author'); foreach ($postsGroupedByAuthor as $authorPosts) { $authorPosts->model(); // returns posts' author $authorPosts->collection(); // returns author's posts }
嵌套分组:首先按类别分组产品,然后按制造商分组。
$products = Product::all(); $groupedProducts = (new CollectionGroupedByModel($products)) ->groupByModel('category_id', 'category') ->transform(function (CollectionGroupedByModel $productsGroupedByCategory) { return $productsGroupedByCategory->groupByModel('manufacturer_id', 'manufacturer'); }); foreach ($groupedProducts as $categoryProducts) { $categoryProducts->model(); // returns category foreach ($categoryProducts->collection() as $manufacturerProducts) { $manufacturerProducts->model(); // returns manufacturer $manufacturerProducts->collection(); // returns products grouped by category and manufacturer } }
按多个模型分组
$posts = Post::all() $postsGroupedByAuthorAndCategory = (new CollectionGroupedByModel($posts)) ->groupByModel(function (Post $post) { return "$post->author_id,$post->category_id"; }, function (Post $post) { return [$post->author, $post->category]; }); foreach ($postsGroupedByAuthorAndCategory as $authorPostsInCategory) { list($author, $category) = $authorPostsWithCategory->model(); // or using php 7.1 array destruction [$author, $category] = $authorPostsWithCategory->model(); $authorPostsWithCategory->collection(); // returns author's posts in category }
安全性
如果您发现任何与安全性相关的问题,请通过电子邮件 amelihovv@ya.ru 联系,而不是使用问题跟踪器。
致谢
此包是通过melihovv/laravel-package-generator的帮助启动的。