skip to Main Content

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

2

Answers


  1. 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 .

    Login or Signup to reply.
  2. $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;
    });
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search