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

查看:292
本文介绍了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查询生成器中有没有不用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天全站免登陆