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


You should try the following:

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

+3


source


Try it,

If your user id is in a variable $user_id

, you can do this for example



DB::table('post')->whereIn('post_id',
    DB::table('watchhistory')->where('user_id',$user_id)->pluck('post_id')
)->get();

      

+2


source







All Articles