Laravel Eloquent - 获取相关模型的最后插入

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/38912439/
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-09-14 14:18:19  来源:igfitidea点击:

Laravel Eloquent - get last insert of related model

phplaraveleloquentlaravel-5.2

提问by Scarwolf

I have a relationship between two models: Terminaland terminalRent.

我有两个模型之间的关系:TerminalterminalRent

A Terminal can have many terminalRents. I want to get the last Rent for a specific Terminal.

一个终端可以有多个终端租金。我想获得特定终端的最后租金。

$lastRent = Terminal::with('terminalRent')->where('id', $id)->orderBy('id', 'desc')->first();

When using where()it will reflect those on the Modalhoewever I want to get the last record for terminalRent in relation to the specific terminal. $idis the Id of the terminal and the tables are connected like this:

使用where()时它将反映那些Modal我想获得与特定终端相关的 terminalRent 的最后一条记录。$id是终端的 ID,表格的连接方式如下:

Terminal
----
ID


terminalRent
-----
ID
terminal_id <--- this is the foreign key for the ID of the Terminal Table

回答by ExohJosh

If the relationship between Terminal and Terminal rent is hasMany you can do something like:

如果终端和终端租金之间的关系是 hasMany 你可以这样做:

$lastRented = $lastRent->terminalRent->last();

Ensure you have the last rented via dd($lastRented);

确保您有最后一次租借通过 dd($lastRented);

Let me know how you get on

让我知道你是怎么办的

Edit: If this gives you the incorrect instance of terminalRent try first(); I can't remember how Eloquent orders eagerlaoded relationships by default.

编辑:如果这给你错误的 terminalRent 实例,请尝试 first(); 我不记得默认情况下 Eloquent 是如何命令急切的关系的。

回答by Parithiban

Try This Code

试试这个代码

$lastRent =  Terminal::with(['terminalRent' => function ($query) { 
                        $query->orderBy('id', 'desc')->first();
                }]);

回答by Ivanka Todorova

You can join them and then order the results based on terminalRent.idand pick the first one:

您可以加入它们,然后根据结果排序terminalRent.id并选择第一个:

$lastRent = Terminal::join('terminalRent', 'terminalRent.terminal_id','=','Terminal.id')->where('Terminal.id', $id)->orderBy('terminalRent.id', 'desc')->first();

回答by Adrenaxus

Use this to get the last rent for a specific Terminal:

使用它来获取特定终端的最后租金:

$terminal = Terminal::find($id); //the terminal for which you want to get the last rent
$lastRent = $terminal->rentals()->orderBy('id', 'DESC')->first();

Keep in mind that this is only one way to do it, there might be other options that suit your needs better.

请记住,这只是一种方法,可能还有其他更适合您需求的选择。