相关文章推荐
会开车的企鹅  ·  python ...·  5 天前    · 
会开车的企鹅  ·  php - Laravel Query ...·  6 月前    · 
会开车的企鹅  ·  PolarDB 数据库内核月报·  7 月前    · 
会开车的企鹅  ·  js 字符串 string \n \\ ...·  10 月前    · 
会开车的企鹅  ·  PHP: ...·  1 年前    · 
会开车的企鹅  ·  analysis of rtsp | ...·  1 年前    · 
坏坏的麦片  ·  SqlParameter.Value ...·  2 小时前    · 
爱旅游的铁链  ·  Uses of Class ...·  2 小时前    · 
独立的红豆  ·  SqlParameter ...·  2 小时前    · 
聪明伶俐的课本  ·  SpringBoot ...·  4 小时前    · 
Collectives™ on Stack Overflow

Find centralized, trusted content and collaborate around the technologies you use most.

Learn more about Collectives

Teams

Q&A for work

Connect and share knowledge within a single location that is structured and easy to search.

Learn more about Teams

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)'));

Any idea to make it better?

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();

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();

That, of course, requires that you have a model that extends 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.

 // 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 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.).

@Shiro toArray() is a model method of Eloquent, not of DB. You will need to use whereRaw() instead. I have updated my answer. – Tim Groeneveld Apr 15, 2014 at 5:05 @ErikBerkun-Drevnig, I have edited my post. I did write this answer so it could be used for any field. Also note that the original answer did not limit the query from returning more then one row. This is (IMHO) an important thing to note. For example, if I wanted to use this query to find user profiles with max(age) and min(age). I would not want to limit my results to one row. – Tim Groeneveld Dec 4, 2016 at 22:34 I would like to get the whole record,not only the max id, and I do not want make it two queries. – Shiro Apr 15, 2014 at 1:47 @Shiro Sorry, you will have to perform a query chain for this, as laravel's fluent query builder will not allow this to be done as a single string, good luck – Ohgodwhy Apr 15, 2014 at 2:17 I needed the next ID: protected function find_next_id_number() { return Module::max('id') + 1; } – dustbuster Feb 1, 2019 at 20:15 Be careful when using ->max('id') with SoftDeletes ... For some reason it doesn't count "Trashed" items ... – Bart Mommens Jun 30, 2022 at 21:06

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

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

Laravel 5+:

  DB::table('orders')->orderBy('id', 'desc')->value('id');
                This is a terrible solution. It forces MySQL to look at all your rows, filter them, sort them, and then return the result. Don't do this. Instead opt for something along the lines of Orders::max('id')
– Edward
                Oct 29, 2018 at 13:11
                @Edward why would this be terrible? If the table had an index on it (which as an 'id' most likely does) then the DB would handle that fine, as simplest order by.
– tristanbailey
                Jul 25, 2021 at 12:12
                Ran a test and Laravel optimises it to select * from `orders` order by `id` desc limit 1 so not pulling all results as limit is set. If there was no key it would need to do more work.
– tristanbailey
                Jul 25, 2021 at 12:22

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.

You can get the latest record added to the Orders table you can use an eloquent method to retrieve the max aggregate:

$lastOrderId = Order::max('id');

To retrieve a single row by the id column value, use the find method:

$order = Order::find(3);

So combining them, to get the last model added to your table you can use this:

$lastOrder = Order::find(Order::max('id'));
                Its nice code, but has to be inefficient right? As max() performs an extra select on the database in this case.
– RonnyKnoxville
                Mar 10, 2023 at 12:09
        

Thanks for contributing an answer to Stack Overflow!

  • Please be sure to answer the question. Provide details and share your research!

But avoid

  • Asking for help, clarification, or responding to other answers.
  • Making statements based on opinion; back them up with references or personal experience.

To learn more, see our tips on writing great answers.

 
推荐文章