xTheWolf
xTheWolf

Reputation: 1886

Laravel Eloquent - get last insert of related model

I have a relationship between two models: Terminal and terminalRent.

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 Modal hoewever I want to get the last record for terminalRent in relation to the specific terminal. $id is the Id of the terminal and the tables are connected like this:

Terminal
----
ID


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

Upvotes: 9

Views: 15565

Answers (5)

MirVan
MirVan

Reputation: 11

@Parithiban Solution is very useful but this function run one query two times

for better performance try this

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

Upvotes: 1

Parithiban
Parithiban

Reputation: 1656

Try This Code

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

Upvotes: 3

Adrenaxus
Adrenaxus

Reputation: 1613

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.

Upvotes: 0

Ivanka Todorova
Ivanka Todorova

Reputation: 10219

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

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

Upvotes: 1

ExohJosh
ExohJosh

Reputation: 1892

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

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

Ensure you have the last rented via 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.

Upvotes: 16

Related Questions