在laravel中从union和paginate的子查询中选择

时间:2018-11-08 08:15:53

标签: php laravel

我有一个MySql脚本,当以PHP本机运行时,该脚本运行良好。

SELECT * FROM (
(SELECT * FROM news WHERE ctg = 'Promotion' and active = '1' ORDER BY id)
  UNION ALL
(SELECT * FROM news WHERE ctg ='Info' ORDER BY id)    
) AS hasil
ORDER BY id DESC

目前,我正在学习如何以laravel雄辩的方式进行操作。这是脚本:

$promo  = DB::select("SELECT * FROM (
(SELECT * FROM news WHERE ctg = 'Promotion' and active = '1' ORDER BY id)
  UNION ALL
(SELECT * FROM news WHERE ctg ='Info' ORDER BY id)
) AS hasil
ORDER BY id DESC ");
return view('news', ['promo' => $promo]);

上面的脚本也可以很好地工作,除非它不能自动解析分页。
那么我应该怎么做才能得到正确的结果,它也可以解析分页?

1 个答案:

答案 0 :(得分:1)

我不知道您为什么在这种情况下使用Union,结果似乎与OR条件相同,请在News模型中尝试

$promo = News::where(function($query){
        $query->where('ctg', '=', 'Promotion')
            ->where('active', '=', '1');
    })
    ->orWhere('ctg', '=', 'info')
    ->orderBy('id', 'DESC')
    ->paginate(10);
return view('news', ['promo' => $promo]);