复杂的查询语句,使用框架默认的 paginate 方便前端接口保持不动。比如
SELECT
p.id AS patient_id,
p.date_left AS date_left,
r.published_count AS published_count,
(CASE WHEN (p.date_left BETWEEN -1 AND 3 AND r.published_count IS NULL) THEN 0 ELSE 1 END) AS warn_level
FROM
(SELECT id, created_at, DATEDIFF(CURDATE(), predicted_published_at) AS date_left FROM patients) p LEFT JOIN
(SELECT patient_id, COUNT(*) AS published_count FROM reports WHERE is_published IS TRUE GROUP BY patient_id) r
ON p.id = r.patient_id
ORDER BY warn_level ASC, p.created_at DESC;
看到这的时候我很震惊的,很复杂的了。为了便于展示,我们还是来个简单的。
$sql = '(select * from users)';
\DB::table(\DB::raw($sql))->paginate(10);
如果报错,比如 : 1248 Every derived table must have its own alias
请使用下边的代码测试。推测和数据库版本有关系。
$sql = '(select * from users) cc';
$v = \DB::table(\DB::raw($sql))->paginate(10);
在这里里面 $sql 充当了 *临时表, 可以是更为复杂的联合查询,
这样我们不仅可以使用 where 还可以使用其他构建器, paginate 这种分页肯定是很多人的最爱;
需要注意的是: sql 字符串是用 括号** '()' 括起来的, 还有cc**这个别名
测试环境:Laravel5.5 Mysql5.7
参考博文: https://blog.csdn.net/qq_26452719/article/details/79583019