I have a field called language in my table submission. Here the different user has submitted their problem with different language such as java(56) 5 times, CPP(45) 7 times, and python(71) 10 times.
I want to have a query in laravel with eloquent such that it returns an array or with key-value pair as
$user_lang = ['56'=>5,'45'=>7,'71'=>10]
here 56,45,71 are the id of the languages
CodePudding user response:
If you have prepared data like count of how many times, you can simply use pluck method. eg
$user_lang = Language::where(<condition>)->pluck('times', 'id');
It will return the array as you desired.
If you do not have prepared count, then count it using group by and simply use same pluck method .
CodePudding user response:
$result = Submission::selectRaw('id', 'COUNT(DISTINCT id) AS times'))
->groupBy(id)
->get();
$user_lang = [];
$result->map($result, function($item){
$user_lang[$item->id] = $item->times;
});