简体   繁体   中英

Laravel Eloquent GroupBy Name to Create array of ID's

I have a table in my Laravel application which I wish to query.

id | company_name | contact |
-----------------------------
1  | Tesco        | Name 1  |
2  | Tesco        | Name 2  |
3  | Asda         | Name 3  |
4  | Tesco        | Name 4  |
5  | Asda         | Name 5  |

I'm trying to get an array of all unique company names with all ID numbers.

'Tesco' => [1,2,4]
'Asda' => [3,5]

I have tried

$companies = Contact::select('company_name','id')->groupBy('company_name')->get();

However this requests the 'id' to be included in the group by which defeats the purpose. I understand it's asking for this because it's not a SUM or COUNT etc.

The above table may seem unusual and I know I should have a relation to a companies table however this is necessary at this stage.

You could use GROUP_CONCAT()

$companies = Contact::select('company_name', DB::raw('GROUP_CONCAT(id) as ids'))
    ->groupBy('company_name')
    ->get();

This would return something like:

company_name | ids
Tesco        | 1,2

Edit: if you want the ids in the form an array, you could just map over the collection to convert it:

$companies->map(function($column) {
    $column->ids = explode(',', $column->ids);
});

That should do the trick.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM