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

9

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

一个终端可以有许多终端租赁。

我想获取特定终端的最后一个租赁。

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

使用where()时,它会反映在Modal上,但我想获取与特定终端相关的terminalRent的最后一条记录。$id是终端的ID,表格连接如下:

Terminal
----
ID


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

你正在使用哪个版本的Laravel? - Adrenaxus
@Adrenaxus 我正在使用5.2版本。 - xTheWolf
5个回答

16

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

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

请确保您已经通过dd($lastRented);获取了最新的租赁记录。

让我知道你的进展情况。

编辑:如果这给出了错误的terminalRent实例,请尝试使用first(); 我不记得Eloquent如何默认排序急加载关系。


这段代码非常好用: $lastRent = Terminal::with('terminalRent')->where('id', $id)->orderBy('id', 'desc')->first(); $lastRented = $lastRent->TerminalRent->first(); 我只是不太明白,因为我使用了两次 first(),所以有点令人困惑。你能解释一下吗?谢谢 - xTheWolf
当然 - 所以,我们有两种常用的完成查询的方式,get(); 和 first(); - 运行 get(); 将返回一个集合,而 first 则从该查询中返回一个单个对象,在您的情况下,关系 TerminalRent 返回一个集合,通过调用 first(); 您可以获得该对象的第一个实例。您可以通过访问 Laravel 文档集合方法并在其中测试任何方法来证明它是一个集合。 - ExohJosh
在您的情况下,您可以像这样做:$lastRent = Terminal::with('terminalRent')->where('id', $id)->get(); $lastRented = $lastRent->TerminalRent->first(); :) - Maraboc
@Maraboc,这个不起作用Undefined property: Illuminate\Database\Eloquent\Collection::$TerminalRent。但是Terminal´Rent确实存在,因为我已经在使用它了,哈哈。无论如何谢谢:) @excojish 谢谢! - xTheWolf
试试这个:$lastRent = Terminal::with('terminalRent')->where('id', $id)->get(); $lastRented = $lastRent->TerminalRent()->orderBy('id', 'DESC')->first(); - Maraboc
@Maraboc 这行代码不会起作用,$lastRent 不会包含属性 TerminalRent,因为它是一个集合。他需要通过循环来访问 TerminalRent 属性。 - ExohJosh

3
尝试这个代码。
$lastRent =  Terminal::with(['terminalRent' => function ($query) { 
                        $query->orderBy('id', 'desc')->first();
                }]);

1

@Parithiban的解决方案非常有用,但这个函数会运行两次查询

为了更好的性能,请尝试这样做

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

1

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

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

0
使用此功能可获取特定终端的最后租金:
$terminal = Terminal::find($id); //the terminal for which you want to get the last rent
$lastRent = $terminal->rentals()->orderBy('id', 'DESC')->first();

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


rentals()是什么?应该是TerminalRent-Model吗? - xTheWolf
rentals()rents()(我不确定拼写)将是您的终端模型中定义的终端和租赁之间的关系:public function rents(){return $this->hasMany('Rent');} - Adrenaxus
啊,好的,谢谢。不幸的是,这也不起作用,因为我得到了其他终端返回的行。 - xTheWolf
请具体说明哪里出了问题。我已经测试过我的1:n关系,它绝对是有效的。 - Adrenaxus

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接