Laravel查询生成器最大ID [英] Laravel Query Builder where max id

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

问题描述

如何在Laravel 4.1查询生成器中完成此操作?

How do I accomplish this in Laravel 4.1 Query Builder?

select * from orders where id = (select max(`id`) from orders)

我尝试了这一点,可以正常工作,但无法获得雄辩的功能.

I tried this, working but can't get the eloquent feature.

DB::select(DB::raw('select * from orders where id = (select max(`id`) from orders)'));

有更好的想法吗?

推荐答案

您应该能够在订单表上执行选择,使用原始WHERE在子查询中找到max(id),如下所示:

You should be able to perform a select on the orders table, using a raw WHERE to find the max(id) in a subquery, like this:

 \DB::table('orders')->where('id', \DB::raw("(select max(`id`) from orders)"))->get();

如果要使用Eloquent(例如,以便将响应转换为对象),则需要使用whereRaw,因为如果不使用Eloquent模型,某些功能(例如toJSONtoArray)将无法使用.

If you want to use Eloquent (for example, so you can convert your response to an object) you will want to use whereRaw, because some functions such as toJSON or toArray will not work without using Eloquent models.

 $order = Order::whereRaw('id = (select max(`id`) from orders)')->get();

这当然要求您拥有一个扩展Eloquent的模型.

That, of course, requires that you have a model that extends Eloquent.

 class Order extends Eloquent {}

如评论中所述,您无需使用whereRaw,您可以使用查询构建器来执行整个查询,而无需使用原始SQL.

As mentioned in the comments, you don't need to use whereRaw, you can do the entire query using the query builder without raw SQL.

 // Using the Query Builder
 \DB::table('orders')->find(\DB::table('orders')->max('id'));

 // Using Eloquent
 $order = Order::find(\DB::table('orders')->max('id'));

(请注意,如果id字段不是唯一的,您将只返回一行-这是因为find()只会从SQL Server返回第一个结果.)

(Note that if the id field is not unique, you will only get one row back - this is because find() will only return the first result from the SQL server.).

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

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