laravel groupby 与数组

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/46665867/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 16:46:55  来源:igfitidea点击:

laravel groupby with array

phpmysqlarrayslaravellaravel-5

提问by scott

i have post with category

我有类别的帖子

 $response=Post::groupBy('post_category','id')->get();

The above query will return all posts with category in the order of category.

上面的查询将按照类别的顺序返回所有具有类别的帖子。

Now i need to group all post inside category. Now i have one possible solution is i need to loop response and inside loop i have to check for category and create array. Is there a option to make it in a query something like groupconcat.?

现在我需要对类别内的所有帖子进行分组。现在我有一个可能的解决方案是我需要循环响应和内部循环我必须检查类别并创建数组。是否有一个选项可以在查询中创建它,例如groupconcat.?

My question is: Is it possible to create an array of category so key of an array is category_nameand inside of category all post?

我的问题是:是否可以创建一个类别数组,以便数组的键是category_name和类别内的 all post

Updated

更新

Post table

岗位表

id | post_name | post_description | category_name | etc..

Here category name is not using any other table since its predefined values like news, sports, cricket something like... When i am inserting news, sports, political in categoryname.

这里的类别名称没有使用任何其他表格,因为它的预定义值如新闻、体育、板球之类的......当我在categoryname.

采纳答案by Praveen Tamil

The following code will return the key, value pair of post with unique category_name

以下代码将返回具有唯一 category_name 的帖子的键值对

$response = Post::get()->groupBy('category_name');
/*
    [
        'category_1' => [
            ['category_name' => 'category_1', 'post_name' => 'Chair'],
            ['category_name' => 'category_1', 'post_name' => 'Bookcase'],
        ],
        'category_2' => [
            ['category_name' => 'category_2', 'post_name' => 'Desk'],
        ],
    ]
*/

回答by aaron0207

You can't do it with a query, SQL group by will keep only one post for category so your query is incorrect. What you are looking for is:

你不能用查询来做到这一点,SQL group by 将只保留一个类别的帖子,所以你的查询是不正确的。您正在寻找的是:

$response = Post::get();
$response = $response->groupBy('post_category');

It will return a collection of arrays keyed by 'post_category' and containing all post from this category.

它将返回以“post_category”为键的数组集合,并包含该类别中的所有帖子。