0

I have the following 2 tables ,

users                    keys

 id   name                id    key   customerid      date
 ___________             ____________________________________
  1    1name               1     1        1        2016-11-17
  2    2name               2     1        1        2016-11-19      
                           3     2        1        2016-11-18
                           4     1        1        2016-11-18

I want to get for every customer the ids of each key having the max date

Customers::with(['keys => function($query){
    $query->groupBy('key')
          ->select('id',DB::raw('max(date)'));
}])
->get();

Now I'm getting the max date and the id of the first row not the id of the record having the max date

Nour Nehme
  • 31
  • 2
  • @Strawberry this is the second time I open this question and everytime it's marked as duplicate knowing that it's not duplicate. I'm searching for an answer in laravel , the answer you provide is pure mysql which don't help me and it's not what I'm asking for. – Nour Nehme Nov 21 '16 at 13:39
  • What's wrong with DB::raw? – Strawberry Nov 21 '16 at 13:41
  • @strawberry in my query I'm using ' with' in this case not everything works with DB::raw, – Nour Nehme Nov 21 '16 at 13:44
  • I suggest you revise the question, identifying the parts of the problem which you do understand, and the parts which you don't - i.e. the way in which existing answers fail to address this particular problem. – Strawberry Nov 21 '16 at 13:47
  • This definitely isn't a duplicate, not the linked reference anyway. Surely those who would like to know how to do this eloquently would benefit - not everyone is comfortable mixing their 'fluent' code with raw queries. It's kinda bias -- nope, this is a duplicate because we've provided a way to do it in Python, meanwhile you're working with PHP. @Nour Nehme, it's clear you're just going to be flagged as duplicate here, but if you try on another site, perhaps remove the `mysql` tag and keep it as `laravel` only and note in your question that you're not looking for a raw query solution. – Stephen Lake Nov 21 '16 at 19:34

0 Answers0