문제

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.

도움이 되었습니까?

해결책

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();
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top