3

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.

1
  • Does this query correct ? What is for WHERE user_id = user_id ? Commented Jul 31, 2017 at 6:18

2 Answers 2

3

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 !!!!

Sign up to request clarification or add additional context in comments.

4 Comments

Actually i tried this first before asking the question. The problem here is that I get an error saying that user_id is not defined, although it was defined within the scope.
@SaviourTom because you have to use this variable in function like use ($user_id) after function($query) so it will look like: function($query) use ($user_id). By the way answer which you've voted as the best answer is by using Query Builder and not the Eloquent.
I was thinking why it was'nt working. Thanks a lot for the answer. @forexknight
Oh! thank @forexknight to draw my attention on use()
2

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();

2 Comments

Thanks a lot for the answer. It works. But i wanted to use eloquent so as to optimize performance.
I've thought you are not using eloquent so I've added my answer

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.