php Laravel 查询生成器,其中最大 id

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/23073214/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 16:28:04  来源:igfitidea点击:

Laravel Query Builder where max id

phplaravelquery-builder

提问by Shiro

How do I accomplish this in Laravel 4.1 Query Builder?

如何在 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)'));

Any idea to make it better?

有什么想法可以让它变得更好吗?

回答by Tim Groeneveld

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:

您应该能够对 orders 表执行选择,使用原始 WHEREid在子查询中查找 max( ),如下所示:

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

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 toJSONor toArraywill not work without using Eloquent models.

如果您想使用 Eloquent(例如,这样您可以将您的响应转换为一个对象),您将需要使用 whereRaw,因为如果不使用 Eloquent 模型,诸如toJSON或 之类的某些功能toArray将无法工作。

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

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

当然,这需要你有一个扩展 Eloquent 的模型。

 class Order extends Eloquent {}

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.

正如评论中提到的,您不需要使用whereRaw,您可以使用查询构建器执行整个查询,而无需原始 SQL。

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

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

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

(请注意,如果该id字段不是唯一的,则只会返回一行- 这是因为find()只会从 SQL 服务器返回第一个结果。)。

回答by Ohgodwhy

Just like the docs say

就像文档说的

DB::table('orders')->max('id');

回答by Afraz Ahmad

For Laravel ^5

对于 Laravel ^5

Orders::max('id');

I used it is short and best;

我用它是简短而最好的;

回答by Govind Samrow

No need to use sub query, just Try this,Its working fine:

不需要使用子查询,试试这个,它工作正常:

  DB::table('orders')->orderBy('id', 'desc')->first();

回答by tristanbailey

For objects you can nest the queries:

对于对象,您可以嵌套查询:

DB::table('orders')->find(DB::table('orders')->max('id'));

So the inside query looks up the max id in the table and then passes that to the find, which gets you back the object.

因此,内部查询在表中查找最大 id,然后将其传递给 find,它使您返回对象。