M
M
mrdragon90002019-03-09 09:37:23
Laravel
mrdragon9000, 2019-03-09 09:37:23

How to make select on two-level with?

User, Ticket, TicketMessage
User hasMany Ticket, Ticket hasMany TicketMessage
Everything seems to be clear here. A user can have many tickets, tickets can have many messages, and each ticket message must have a sender (the sender is marked in the TicketMessage.from_id field.
You need to load the Ticket with all its TicketMessages from the database, and also that the TicketMessages has information about the sender loaded. But, not all information about the sender is needed, but only the First Name and Last
Name.To my surprise, this code returns just null in the TicketMessage.user field, instead of the first and last name about the sender

\Request::user()->tickets()->with('messages.user')->select('users.name', 'user_surname')->find($id);

If you change the TicketMessage association like this:
class TicketMessage
...        
public function user()
{
   return $this->belongsTo('App\User', 'from_id')->select('name', 'surname');
}

TicketMessage.user is still null
How to make this code work properly so that TicketMessage is not null, but the sender information?
\Request::user()->tickets()->with('messages.user')->select('users.name', 'user_surname')->find($id);

Answer the question

In order to leave comments, you need to log in

1 answer(s)
N
Nikolay, 2019-03-09
@mrdragon9000

As already correctly noted, we must not forget about the id in your connection. You can also do it dynamically. In Laravel 5.5 and above, you can try doing this:
Well, or something like this:

\Request::user()->tickets()->with(['messages.user'=>function($query){
        $query->select('id', 'name', 'surname');
    }])->get();

PS Perhaps in all cases it is necessary to return from_id so that the connection can be resolved. You have to try.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question