V
V
Vasyl Fomin2017-04-21 11:39:09
Laravel
Vasyl Fomin, 2017-04-21 11:39:09

Request to Eloquent. How to select 4 latest entries from each category?

There is, for example, a table posts, it has records with fields id, title, category_id, created_at, (each record can belong to one category category_id)
I can’t figure out how to write a query to pull the postslast four records from each category from the table ... as I understand it like that need to group them

Answer the question

In order to leave comments, you need to log in

1 answer(s)
H
hakkol, 2017-04-21
@fomvasss

If I understand you correctly, you can do this:

$categories = Category::with(['posts' => function($query) {
    $query->orderBy('created_at', 'desc')->take(4);
}])->get();

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question