How do I write the following SQL query in Laravel using Eloquent?
I want to write a request in Laravel to get all messages that a specific user has viewed. user_id
and post_id
are saved in a table named WatchHistory
.
SELECT *
FROM Post
WHERE post_id = (
SELECT post_id
FROM WatchHistory
WHERE user_id = $user_id
);
I tried the following:
$posts = Post::whereIn('post_id', function($query){
$query->select('post_id')
->from(with(new WatchHistory)->getTable())
->where('user_id',$user_id);
})->get();
But it gives me the error that the user_id variable is not defined.
+3
source to share
2 answers