如何使用Eloquent在Laravel中编写以下SQL查询?
我想在Laravel中编写一个查询,以检索特定用户查看过的所有帖子。如何使用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){
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,所以我添加了我的答案