Laravel查询构建器 - Union All with Skip and Take

时间:2014-08-06 01:18:57

标签: php laravel-4 eloquent query-builder

我需要使用此查询从表中获取数据:

(select columns 
   from tableX 
   join tableZ 
   on tableX.id1 = tableZ.other_id)
union all 
(select columns 
   from tableX 
   join tableZ 
   on tableX.id2 = tableZ.other_id) 
LIMIT num1, num2

如果没有LIMIT,我的查询构建器会得到正确的结果(让$first成为select的第一个查询,$second是另一个选择查询):

$first->unionAll($second)->get();

当我尝试放置skip和/或take时,结果与上面的第一个查询不同。

$first->unionAll($second)->take(num1)->skip(num2)->get();

上述构建器的结果查询(我从DB::getQueryLog()获得)类似于:

(select columns 
   from tableX 
   join tableZ 
   on tableX.id1 = tableZ.other_id LIMIT num1, num2)
union all 
(select columns 
   from tableX 
   join tableZ 
   on tableX.id2 = tableZ.other_id)

哪一个产生不正确的结果。有谁知道做出第一个查询的工作是什么?谢谢!

2 个答案:

答案 0 :(得分:2)

You need to wrap $firstQuery in another query, like this:

$first->unionAll($second);

$rows = DB::table( DB::raw("({$first->toSql()}) as t") )
->mergeBindings($first->getQuery())
->take(num1)->skip(num2)
->get();

This will result in the following query:

select * from (FIRST_QUERY union all SECOND_QUERY) as t limit num1, num2

答案 1 :(得分:0)

一种解决方法是在下面的示例块中使用DB :: select和DB :: raw进行原始查询...

    $num1 = 100; // skip first 100 rows
    $num2 = 2;   // take only 2 rows 

    $qry_result = DB::select(DB::raw("select * from 
          (
            (select columns from tableX join tableZ on tableX.id1 = tableZ.other_id)
             union all 
            (select columns from tableX join tableZ on tableX.id2 = tableZ.other_id) 
          ) Qry LIMIT :vskip , :vlimit ") , array('vskip'=>$num1,'vlimit'=>$num2) 
   );