Php Laravel查询生成器-使用Skip和Take合并所有查询
我需要使用此查询从表中获取数据:Php Laravel查询生成器-使用Skip和Take合并所有查询,php,laravel-4,eloquent,query-builder,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 如果没有限制,我将使用查询生成器获得如下所示的正确结果(让$fir
(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
如果没有限制
,我将使用查询生成器获得如下所示的正确结果(让$first
作为select的第一个查询,$second
作为另一个select查询):
当我尝试放置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)
这当然会产生错误的结果。有人知道第一个查询的工作是什么吗?谢谢 一种解决方法是在下面的示例块中使用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)
);
您需要在另一个查询中包装
$firstQuery
,如下所示:
$first->unionAll($second);
$rows = DB::table( DB::raw("({$first->toSql()}) as t") )
->mergeBindings($first->getQuery())
->take(num1)->skip(num2)
->get();
这将导致以下查询:
select * from (FIRST_QUERY union all SECOND_QUERY) as t limit num1, num2
对不起。我的问题很久以前就得到了回答,但你忘了接受纳伦德拉的答案,但你还是投了更多的票。
select * from (FIRST_QUERY union all SECOND_QUERY) as t limit num1, num2