Laravel - 使用查询生成器命名子查询 [英] Laravel - named subquery using Query Builder

查看:46
本文介绍了Laravel - 使用查询生成器命名子查询的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

MySQL 子查询 文档中有一个子查询示例:

In MySQL subqueries documentation there's an exmaple of subquery:

SELECT ... FROM (subquery) [AS] name ...

这是我要转换的原始查询:

Here's the raw query which I want to transform:

select SUBQUERY_NAME.* from (select id, name from items) AS SUBQUERY_NAME

在 Laravel Query Builder 中有什么方法可以在不使用 DB::raw() 的情况下做到这一点?

Is there any way to do this in Laravel Query Builder without using DB::raw()?

推荐答案

不幸的是没有.查询构建器有其局限性,更复杂的查询超出了它的范围,这就是 DB::raw() 存在的原因.但是,如果你想让它更优雅一点并使用查询生成器生成子查询,你可以这样做:

Unfortunatelly no. The Query Builder has its limitations and more complex queries are outside its scope, that's why DB::raw() is there. But, if you want to make it a little more elegant and generate the subquery using the Query Builder, you could do something like this this:

$subquery = DB::table('items')->select('id', 'name')->toSql();
DB::table(DB::raw($subquery . ' as subquery_name'))->select('subquery_name.*');

这篇关于Laravel - 使用查询生成器命名子查询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆