Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/sql/68.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何使用Eloquent在Laravel中编写以下SQL查询?_Sql_Laravel_Eloquent_Subquery - Fatal编程技术网

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

如何使用Eloquent在Laravel中编写以下SQL查询?,sql,laravel,eloquent,subquery,Sql,Laravel,Eloquent,Subquery,我想在Laravel中编写一个查询,以检索特定用户查看过的所有帖子。user\u id和post\u id保存在名为WatchHistory的表中 SELECT * FROM Post WHERE post_id = ( SELECT post_id FROM WatchHistory WHERE user_id = $user_id ); 我尝试了以下方法: $posts = Post::whereIn('post_id', function($query){

我想在Laravel中编写一个查询,以检索特定用户查看过的所有帖子。
user\u id
post\u id
保存在名为
WatchHistory
的表中

SELECT *
FROM Post
WHERE post_id = (
     SELECT post_id
     FROM WatchHistory
     WHERE user_id = $user_id
);
我尝试了以下方法:

$posts = Post::whereIn('post_id', function($query){
        $query->select('post_id')
            ->from(with(new WatchHistory)->getTable())
            ->where('user_id',$user_id);
        })->get();
但是它给了我一个错误,变量user\u id没有定义。

试试这个

如果您的用户id在变量
$user\u id
中,您可以这样做

DB::table('post')->whereIn('post_id',
    DB::table('watchhistory')->where('user_id',$user_id)->pluck('post_id')
)->get();
你应该试试这个:

POST::whereIn('post_id', function($query) use($user_id){
            $query->select('post_id')
                ->from(with(new WATHCHISTORY)->getTable())
                ->where('user_id',$user_id);
            })->get();

希望这项工作为你

这个查询正确吗?什么是用于
的,其中user\u id=user\u id
。这里的问题是,我得到一个错误,说用户id没有定义,尽管它是在范围内定义的。@SaviourTom,因为您必须在函数中使用此变量,如
use($user\id)
function($query)
之后使用
function($query)use($user\id)
。顺便说一句,你认为最好的答案是使用查询生成器,而不是雄辩的。我在想为什么它不起作用。非常感谢你的回答@forexknightOh!感谢@forexknight提请我注意
use()
非常感谢您的回答。它起作用了。但是我想使用eloquent来优化性能。我认为您没有使用eloquent,所以我添加了我的答案