Mysql分组查询问题

是这样的,我有一组这样的数据:
图片描述

这个表中有一个字段first_pinyin,我在laravel中是这样使用的:

$products = Product::groupBy('first_pinyin')->get(['first_pinyin']);

这个结果不是我的本意,我想要的结果是这样的,
得到一个结果集数组或者Collection, key是分组后得到所有出现过的first_pinyin,其对应的值必定是一个数组,里面装有每一条是first_pinyin的记录。
例如数据下面这种格式的。

[
    'a' => [
        ['id' => 1, 'name' => '艾提科信传媒有限公司'],
        ['id' => 29, 'name' => '爱上网公司']
    ],
    'b' => [],
    'c' => [],
    ...
]

请问我在laravel中如何操作可以得到这样的结果集, 或者提供一下mysql的思路。 谢谢。

阅读 4.4k
6 个回答
$products = Product::all()->groupBy('first_pinyin');

这个就是了,如果想要你说的结果,后面再加一个->toArray()

新手上路,请多包涵
 $list = select * from product  order by first_pinyin 
 $result = [];
 foreach($list as $k => $v) {
    array_push($result[$k],$v);
 }
Call to undefined method Illuminate\Database\Query\Builder::all()

不行, 按理说Builder应该也有all方法的, 但是会报这个错。
现在可以的是:

$products = Product::groupBy('first_pinyin')->get(['first_pinyin']);

只能取first_pinyin,看网上的分组查询语句,好像也是只能查询这样的数据,我对 mysql 不是很精通,

试试:

Product::groupBy('first_pinyin')->get()->groupBy('first_pinyin');

就是就是group by后的行变成列查询

/**
     * @function    map         组装数组
     * @param       array       $data  数据
     * @param       string      $field key
     * @param       string      $value value default null
     * @author      zhangle
     * @date        2018-07-13
     * @return      array
     */
    protected function toMap(array $data, $field = 'id', $value = ‘’){
        $result  = array();

        if(empty($data)){
            return $result;
        }

        //开始处理数据
        foreach ($data as $item) {
            $val = $item;
            if(!empty($value)){
                $val   = $item[$value];
            }
            $result[$item[$field]]  = $val;
        }

        return  $result;
    }
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题