2016-11-11 65 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)可以帮助你更好地理解, –