鍍金池/ 問答/PHP  數(shù)據庫/ Mysql分組查詢問題

Mysql分組查詢問題

是這樣的,我有一組這樣的數(shù)據:
圖片描述

這個表中有一個字段first_pinyin,我在laravel中是這樣使用的:

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

這個結果不是我的本意,我想要的結果是這樣的,
得到一個結果集數(shù)組或者Collection, key是分組后得到所有出現(xiàn)過的first_pinyin,其對應的值必定是一個數(shù)組,里面裝有每一條是first_pinyin的記錄。
例如數(shù)據下面這種格式的。

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

請問我在laravel中如何操作可以得到這樣的結果集, 或者提供一下mysql的思路。 謝謝。

回答
編輯回答
舊顏

就是就是group by后的行變成列查詢

2018年1月31日 20:04
編輯回答
傲嬌范

試試:

Product::groupBy('first_pinyin')->get()->groupBy('first_pinyin');
2018年2月6日 06:17
編輯回答
逗婦惱
 $list = select * from product  order by first_pinyin 
 $result = [];
 foreach($list as $k => $v) {
    array_push($result[$k],$v);
 }
2017年8月7日 02:27
編輯回答
扯不斷
$products = Product::all()->groupBy('first_pinyin');

這個就是了,如果想要你說的結果,后面再加一個->toArray()

2018年7月24日 00:17
編輯回答
孤島
/**
     * @function    map         組裝數(shù)組
     * @param       array       $data  數(shù)據
     * @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;
        }

        //開始處理數(shù)據
        foreach ($data as $item) {
            $val = $item;
            if(!empty($value)){
                $val   = $item[$value];
            }
            $result[$item[$field]]  = $val;
        }

        return  $result;
    }
2018年3月17日 22:39
編輯回答
孤巷
Call to undefined method Illuminate\Database\Query\Builder::all()

不行, 按理說Builder應該也有all方法的, 但是會報這個錯。
現(xiàn)在可以的是:

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

只能取first_pinyin,看網上的分組查詢語句,好像也是只能查詢這樣的數(shù)據,我對 mysql 不是很精通,

2017年3月20日 22:22