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

时间:2016-08-12 07:36:05

标签: php laravel eloquent laravel-5.2

我有两种模式之间的关系:CharStream.from(str).toMultiset().maxOccurrences().get(); Terminal

终端可以有很多终端租用。 我想获得特定航站楼的最后租金。

terminalRent

当使用$lastRent = Terminal::with('terminalRent')->where('id', $id)->orderBy('id', 'desc')->first(); 时,它将反映where()上的那些我希望获得与特定终端相关的terminalRent的最后一条记录。 Modal是终端的ID,表格连接如下:

$id

5 个答案:

答案 0 :(得分:5)

如果终端和终端租金之间的关系已经很多,你可以这样做:

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

确保您最后通过dd($lastRented);

租借

让我知道你是如何上场的

编辑:如果这给你一个不正确的terminalRent实例,请尝试first();我无法记住,Eloquent默认情况下是如何命令eagerlaoded关系的。

答案 1 :(得分:2)

试用此代码

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

答案 2 :(得分:1)

您可以加入他们,然后根据terminalRent.id订购结果并选择第一个:

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

答案 3 :(得分:0)

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

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

请记住,这只是一种方法,可能还有其他选项可以更好地满足您的需求。

答案 4 :(得分:0)

@Parithiban解决方案非常有用,但此功能可运行一次查询两次

为了获得更好的性能,请尝试

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