Reputation: 534
I want to write a query in Laravel to retrive all the posts that a particular user has viewed. The user_id
and the post_id
is saved in the 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 an error that the variable user_id is not defined.
Upvotes: 3
Views: 168
Reputation: 21681
You should try this :
POST::whereIn('post_id', function($query) use($user_id){
$query->select('post_id')
->from(with(new WATHCHISTORY)->getTable())
->where('user_id',$user_id);
})->get();
Hope this work for you !!!!
Upvotes: 3
Reputation: 9369
Try this one,
If your user's id is in variable $user_id
, you can do it like,
DB::table('post')->whereIn('post_id',
DB::table('watchhistory')->where('user_id',$user_id)->pluck('post_id')
)->get();
Upvotes: 2