Laravel 返回一个记录,其中最大值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/45262872/
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
Laravel return one record where max value
提问by Hardist
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.
它有效,我得到了最高的价值。但我想返回整个记录,因此我还可以访问费用名称、created_at 等。
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.
这似乎是一个简单的解决方案,但无处可寻。
回答by Rwd
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:
如果我正确理解您的问题,要获得最高金额的记录,您只需添加一个orderBy
并抓取第一行:
auth()->user()->expenses()->orderBy('amount', 'desc')->first();
This should give the expense
with the highest amount.
这应该给出expense
最高金额。
Hope this helps!
希望这可以帮助!
回答by Sagar Gautam
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.
这将适用于正常情况,即表中只有一个amount
列的最大值。
So long as there isn't a collision with the max
column and another column within the table, this might work.
只要没有与表中的max
列和另一列发生冲突,这可能会起作用。
If there are more than one maximum value this will not work.
如果有多个最大值,这将不起作用。
So, As Ross Wilsonsaid above, You have to order the rows in descending order and get the first row like:
因此,正如Ross Wilson上面所说,您必须按降序对行进行排序并获得第一行,例如:
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
.
这将完美地工作,因为即使有多个max
,这也会为第一行提供该列的最大值amount
。
回答by Abdeldjallil Hadji
You can the Collection method sortByDesc
like follow :
你可以sortByDesc
像下面这样的 Collection 方法:
return auth()->user()->expenses()->sortByDesc('amount')->first();