我想在 Laravel 中编写一个查询来检索特定用户查看过的所有帖子。 user_id
和 post_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_id 没有定义。
最佳答案
你应该试试这个:
POST::whereIn('post_id', function($query) use($user_id){
$query->select('post_id')
->from(with(new WATHCHISTORY)->getTable())
->where('user_id',$user_id);
})->get();
希望这对你有用!!!!
关于sql - 如何使用 Eloquent 在 Laravel 中编写以下 SQL 查询?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45408566/