1

I have the following table setup (just to explain my problem here):

qid | value | created_at
1      1        2014-01-01 00:10
1      2        2014-01-01 00:12
2      231      2014-01-01 00:10
3      hello    2014-01-01 00:10

I would like to get an array with Distinct qids, order by created_at DESC.

So the array should look like (only values for example):

 [2, 231, hello]

Do i need a "Raw Query, with Distinct on the qid column" - or is there another way with Laravel5 ORM Methods?

derdida
  • 14,784
  • 16
  • 90
  • 139

2 Answers2

4

You need to order by created_at and then group by qid.

Answer::orderBy('created_at', 'desc')->groupBy('qid')->get();
BrokenBinary
  • 7,731
  • 3
  • 43
  • 54
  • Thanks! I use now: $Answers = Answer::where('task_uuid', $taskuuid)->orderBy('created_at','desc')->groupBy('question_uuid')->get(); - but i always gets the first value, not the "newest" - so it looks like that he is ignoring the created_at clause. – derdida Jun 22 '15 at 23:27
2

In this case you could add a groupby on qid to achieve that result. Include the order by to ensure you get the desired qid.

e.g.

->groupBy('qid')
Scott Anderson
  • 1,363
  • 1
  • 10
  • 19
  • Thanks! I use now: $Answers = Answer::where('task_uuid', $taskuuid)->orderBy('created_at','desc')->groupBy('question_uuid')->get(); - but i always gets the first value, not the "newest" - so it looks like that he is ignoring the created_at clause. – derdida Jun 22 '15 at 23:27
  • 2
    If this doesn't work for you, you may need to try http://stackoverflow.com/questions/18159465/how-to-order-grouped-results-using-eloquent – Scott Anderson Jun 22 '15 at 23:34
  • oh thanks, i will try that out! Seems that i need to use the raw query method. – derdida Jun 22 '15 at 23:36