Question

I have a table named posts and another one named users. The table posts haves a field user_id.

I need to obtain the last post of the last three registered users. I tried something like this:

Post::with('user')->groupBy('user_id')->orderBy('id','desc')->take(3)->get();

The result is close to what I need, but not exactly, because I'm obtaining the first post of the last three registered users.

thus, I need to know how I can make with Eloquent something like this:

SELECT * FROM (SELECT * FROM posts ORDER BY id DESC)sub GROUP BY user_id LIMIT 3;

I would not want to use raw queries, because, as you can see, I need to retrieve the User objects too.

Était-ce utile?

La solution

You can use raw queries and retrieve the User object too

Post::with('user')
->from(DB::raw('(SELECT * FROM posts ORDER BY id DESC)sub'))
->groupBy('user_id')->take(3)->get();
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top