2016-11-11 61 views
1

如何寫一個複雜的查詢在Laravel 5.3,我嘗試,但結果並不fullfill寫Netsted選擇查詢在Laravel 5.3

查詢是否有

SELECT * FROM (SELECT posts.post_id FROM posts WHERE ((posts.user_id = 1 AND posts.user_type = 'user') OR (posts.user_id IN (1) AND posts.user_type = 'page'))) posts WHERE posts.post_id > '0' ORDER BY posts.post_id DESC 

,我們可以編寫使用Larave模型? 幫我

回答

0

這是你的答案。

$MyQuery = DB::table(DB::Raw("(SELECT 
           posts.post_id 
           FROM 
           posts 
           WHERE 
           (
           (
            posts.user_id = 1 
            AND posts.user_type = 'user' 
           ) 
            OR 
            (
            posts.user_id IN (1) 
            AND posts.user_type = 'page' 
            ) 
           ) 
           )")) 
      ->where('posts.post_id','>',"0")->orderBy("posts.post_id" , "DESC")->get(); 

嘗試打印查詢一次使用->toSql()這樣

echo $MyQuery = DB::table(DB::Raw("(SELECT 
            posts.post_id 
            FROM 
            posts 
            WHERE((
              posts.user_id = 1 
              AND posts.user_type = 'user' 
              ) 
              OR(
              posts.user_id IN (1) 
              AND posts.user_type = 'page' 
              )))")) 
      ->where('posts.post_id','>',"0")->orderBy("posts.post_id" , "DESC")->toSql(); 

      die(); 
+0

此感謝尼斯的答案,但我使用模型來構建SELECT查詢 –

+0

@NarendraJhala [這](http://laravel.io/論壇/ 03-05-2014-nested-query-in-from)可以幫助你更好地理解, –