[英]Laravel Eloquent - get last insert of related model
我有兩個模型之間的關系: Terminal
和terminalRent
。
一個終端可以有多個終端租金。 我想獲得特定終端的最后租金。
$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
如果終端和終端租金之間的關系是 hasMany 你可以這樣做:
$lastRented = $lastRent->terminalRent->last();
確保您通過dd($lastRented);
租了最后一個dd($lastRented);
讓我知道你如何相處
編輯:如果這給你錯誤的 terminalRent 實例,請嘗試 first(); 我不記得默認情況下 Eloquent 是如何訂購急需的關系的。
試試這個代碼
$lastRent = Terminal::with(['terminalRent' => function ($query) {
$query->orderBy('id', 'desc')->first();
}]);
您可以加入它們,然后根據terminalRent.id
對結果進行排序並選擇第一個:
$lastRent = Terminal::join('terminalRent', 'terminalRent.terminal_id','=','Terminal.id')->where('Terminal.id', $id)->orderBy('terminalRent.id', 'desc')->first();
@Parithiban 解決方案非常有用,但此功能運行一次查詢兩次
為了更好的性能試試這個
$lastRent = Terminal::with(['terminalRent' => function ($query) {
return $query->orderBy('id', 'desc')->limit(1);
}]);
使用它來獲取特定終端的最后租金:
$terminal = Terminal::find($id); //the terminal for which you want to get the last rent
$lastRent = $terminal->rentals()->orderBy('id', 'DESC')->first();
請記住,這只是一種方法,可能還有其他更適合您需求的選擇。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.