简体   繁体   中英

Laravel return one record where max value

I'm trying to return one record with a max value as an object. When I do this:

public function highestExpense()
    {
        return auth()->user()->expenses()->max('amount');
    }

It works, and I get the highest value. But I want to have the whole record returned, so I also have access to the expense name, created_at, and so on.

This didn't work for me:

return auth()->user()->expenses()->max('amount')->get();

It seems like a simple solution but the answer is nowhere to be found.

If I'm understanding your question correctly, to get the record that has the highest amount you could just add an orderBy and the grab the first row:

auth()->user()->expenses()->orderBy('amount', 'desc')->first();

This should give the expense with the highest amount.

Hope this helps!

您可以使用 Collection 方法sortByDesc如下:

return auth()->user()->expenses()->sortByDesc('amount')->first();

Normally,

This is your try,

return auth()->user()->expenses()->max('amount')->get();

This will work in Normal case where there is only one maximum value of amount column in the table.

So long as there isn't a collision with the max column and another column within the table, this might work.

If there are more than one maximum value this will not work.

So, As Ross Wilson said above, You have to order the rows in descending order and get the first row like:

auth()->user()->expenses()->orderBy('amount', 'desc')->first();

This will work perfectly because even if there are more than one max , this will give first row with maximum value of the column amount .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM