如何在laravel中获取mysql表的最后一行值?
问题描述:
i want to show the active deposit of my user.therefore i want to get last amount user has deposited in his account. but i have new in Laravel . i have tried following but its sums all amount of user not only last one. if you need i will share whole bunch of code here.
$data['a_deposit'] = Deposit::whereUser_id(Auth::user()->id)->orderBy('id','DESC',LIMIT 1)->take(1)->sum('amount');
from here i want to get last amount
$data['last_deposit'] = Deposit::whereUser_id(Auth::user()->id)->orderBy('id','DESC')->take(6)->get();
我想显示我的用户的有效存款。因此,我希望获得用户已存入其帐户的最后金额 。 但是我在Laravel有了新的东西。 我试过跟随但它的总和所有用户不仅最后一个。 如果你需要我会在这里分享一大堆代码。 p>
$ data ['a_deposit'] = Deposit :: whereUser_id(Auth :: user() - > id) - > orderBy('id','DESC',LIMIT 1) - > take(1) - > sum('amount');
code> pre>
从这里我想得到最后一笔金额 p>
$ data ['last_deposit'] = Deposit :: whereUser_id(Auth :: user() - > id) - > orderBy ('id','DESC') - > take(6) - > get();
code> pre>
div>
答
If you want to get only the last ammount, use value()
:
Deposit::where('user_id', auth()->id())->latest('id')->value('amount');
If you want to get last amount from already loaded collection:
$data['last_deposit'] = Deposit::whereUser_id(Auth::user()->id)->orderBy('id','DESC')->take(6)->get();
You can do this:
$amount = $data['last_deposit']->first()->amount;
答
If you want to get the latest values in your table you can do something like this:
Deposit::latest()->get();
or
Deposit::latest()->first();