简体   繁体   English

如何使用Eloquent在Laravel中编写以下SQL查询?

[英]How do I write the following SQL query in Laravel using Eloquent?

I want to write a query in Laravel to retrive all the posts that a particular user has viewed. 我想在Laravel中编写一个查询来检索特定用户查看过的所有帖子。 The user_id and the post_id is saved in the table named WatchHistory . user_idpost_id保存在名为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. 但它给了我一个错误,即没有定义变量user_id。

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 !!!! 希望这对你有用!!!!

Try this one, 试试这个,

If your user's id is in variable $user_id , you can do it like, 如果您的用户ID在变量$user_id ,您可以这样做,

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM