[英]How do I write the following SQL query in Laravel using Eloquent?
我想在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();
希望這對你有用!!!!
試試這個,
如果您的用戶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.