P
P
palansky2019-08-02 19:38:53
Laravel
palansky, 2019-08-02 19:38:53

How to make such a selection by links?

Greetings! It would seem a simple thing, but I can not get the result.
There are models:
User - hasMany - Room
Room - hasMany - Order
How to get all relationships of a Room, with one last Order entry?
Tried to do like this:

$user->rooms()
    ->with([ 'orders' => function ($query) {
         $query->with('user')->latest()->first();
         }
    ])
->get();

I also tried instead of first() ->take(1)->get()
But I get only one record only for the first connection, and the rest are empty:
[
            0 => [
                'orders' => ['name order']
            ],
            1 => [
                'orders' => []
            ],
            2 => [
                'orders' => []
            ],
        ]

How to get only one record from a link?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
Z
Zlatoslav Desyatnikov, 2019-08-02
@palansky

It is easier to implement the lastOrder relation in the Room model.

public function lastOrder(): HasOne
{
    return $this->hasOne(Order::class, '...')->latest();
}

And in the selection just use
->with('lastOrder')

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question