DarkGhostHunter
DarkGhostHunter

Reputation: 1550

Laravel Query Builder: Get one item from each group

Basically I have a mini-library with multiple books, authors and dates of arrival.

|    Book    |   Author   |   Arrived   | For Sale | 
| ---------- | ---------- | ------------| -------- |
| HPotter V1 | Rowling    | 2010-01-01  | Yes      |
| HPotter V2 | Rowling    | 2010-02-01  | Yes      |
| S.Trek. V1 | Anonymous  | 2010-01-01  | No       |
| LotR. V1   | Tolkien    | 2010-02-01  | Yes      |
| LotR. V2   | Tolkien    | 2010-03-01  | Yes      |
| LotR. V3   | Tolkien    | 2010-04-01  | Yes      |
| LotR. V4   | Tolkien    | 2010-05-01  | Yes      |
| 50Shad. V1 | Satan      | 2010-06-01  | No       |
| Twilight 1 | Satan      | 2010-07-01  | No       |

Basically I need to get only one Book For Sale for Group of Arrived Dates. That means, I have to get one book for each of these dates:

The last two books are not for sale, so they shouldn't be picked - I know it can be filtered with a simple ->where('For Sale', 'Yes').

The main idea is to push everything to the database instead of getting the whole list (it's kinda big) and manipulate it under Laravel.

Upvotes: 0

Views: 546

Answers (1)

Laerte
Laerte

Reputation: 7083

Check if this is what you're looking for:

Book::where('For Sale', 'Yes')->groupBy('Arrived')->get();

Hope it helps...

Upvotes: 1

Related Questions