2017-04-18 38 views
0

我有3個表格:posts,votesusers。我用Eloquent寫了一個整潔的代碼來檢索用戶尚未投票的帖子。如何從Laravel雄辯中的其他表中檢索行?

$posts = Post::whereDoesntHave("votes") 
        ->where('user_id', '=', $user_id) 
        ->whereBetween('posts.created_at', array(Carbon::now()->subHours(48), Carbon::now())) 
        ->take(20) 
        ->get(); 

return response()->json(['posts' => $posts])->withCallback($request->input('callback')); 

但我也想從表用戶檢索用戶名。我想用json傳遞數據。

如果我試圖用查詢生成器來做,很難排除已經被用戶投票過的帖子。

回答

1

你可以做一個手動加入到用戶表

$posts = Post::join('users', 'users.id', '=', 'posts.user_id') 
       ->whereDoesntHave("votes") 
       ->where('user_id', '=', $user_id) 
       ->whereBetween('posts.created_at', array(Carbon::now()->subHours(48), Carbon::now())) 
       ->take(20) 
       ->get(); 

或者你可以在Post模型類中定義relationship

public function user() 
{ 
    return $this->belongsTo('App\User'); 
} 

然後您使用with('user')從用戶表中檢索數據。

$posts = Post::with('user') 
       ->whereDoesntHave("votes") 
       ->where('user_id', '=', $user_id) 
       ->whereBetween('posts.created_at', array(Carbon::now()->subHours(48), Carbon::now())) 
       ->take(20) 
       ->get(); 
+0

謝謝,工作完美! –

+0

但是如果我想檢索相對於當前用戶的帖子。所以現在它刪除已投票的帖子。但是我想刪除當前用戶之前投票過的帖子。 –