Answer the question
In order to leave comments, you need to log in
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);
class TicketMessage
...
public function user()
{
return $this->belongsTo('App\User', 'from_id')->select('name', 'surname');
}
\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
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();
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question