0

My records in 'answers table':

**id    question_id   answer**

  20      12          app/Http/routes.ph
  21      13          uri
  22      13          closure
  23      14          controller
  24      15          class name
  25      15          App\Http\Controllers
  26      16          for displayh

My code to retrieve data:

$qas= DB::table('answers')
         ->groupBy('question_id')
         ->get();
        dump($qas);
    }

I get only 5 records instead of 7; where the other 2 records? It works similarly to distinct function which is not my intention.

How to write code to get all 7 record which are grouped by 'question_id'?

Misterk
  • 633
  • 3
  • 9
  • 17

3 Answers3

0

Understand the concept of GroupBy, its mean that, it will consider same items as one, eg 14, 14-> 14 | 13,13-> 13 if you want to get all answer, then you have to write this

DB::table('answers')->get();

Edited

distinct and group by will do same action in your case. If You can explain your problem in more details, then may be there is possible solution are.

Qazi
  • 5,015
  • 8
  • 42
  • 62
  • My table "answer table' has field: id, question_id, and answer. I want to get all records for answer column, but the records must be categoried or group by question column. – Misterk Feb 19 '16 at 04:50
  • `DB::table('answers')->select('question_id', DB::raw(group_concat(answer SEPARATOR ',') AS ans) )->groupBy('question_id')->get();` for reference have a look [Link 1](http://stackoverflow.com/questions/149772/how-to-use-group-by-to-concatenate-strings-in-mysql?answertab=votes#tab-top) [Link 2](http://stackoverflow.com/questions/15273118/how-to-use-group-by-to-concat-strings-in-mysql?answertab=votes#tab-top) [Link 3](http://www.giombetti.com/2013/06/06/mysql-group_concat/) – Qazi Feb 19 '16 at 05:16
0

You're talking about result with 7 rows, but that's not grouping. Maybe you're talking about ordering instead of grouping? If so, you'd want to use ->orderBy('question_id', 'asc'), that will give you 7 rows, sorted by question_id.

Alexey Mezenin
  • 158,981
  • 26
  • 290
  • 279
0

In SQL, GROUP BY clause is useful when you need to aggregate the result in a sort of way for example for SUM or AVERAGE of data.

Your case is different, you don't need to aggregate data using some function, you simply need a different data structure other than a simply and flat result list.

For your need, you should avoid GROUP BY, and reorder data in your code in a programmatic way.

alberto-bottarini
  • 1,213
  • 9
  • 21