php - Laravel getting latest field in Join table with Eager loading

Laravel version:7.0
I am going to get list fromGuest
model.
guests table: id, name, status, created_at, updated_at
$guests = Guest::orderby("status")->get();
Here ismessages
table.
$messages table: id, message, from_id, from_type, to_id, to_type
from_type
,to_type
can be either guest or user.
If I get latest message with lazy loading, I can get as following.
foreach($guests as $guest)
{
$lastMessage = Message::where(function($query) use($guest){
$query->where("from_id", $guest->id);
$query->where("from_type", "guest");
})
->orWhere(function($query) use($guest){
$query->where("to_id", $guest->id);
$query->where("to_type", "guest");
})->latest()->first();
}
However, I know this is crazy. How can I get this with Eager loading?
Can anyone please give me some instruction?
Answer
Solution:
One solution is to add it as an attribute in the user model as following
public function getLatestMessageAttribute()
{
return Message::where(function($query) use($guest){
$query->where("from_id", $this->id);
$query->where("from_type", "guest");
})
->orWhere(function($query) use($guest){
$query->where("to_id", $this->id);
$query->where("to_type", "guest");
})->latest()->first();
}
Then you need to add to $append array:
protected $appends = ['latest_message'];
Share solution ↓
Additional Information:
Link To Answer People are also looking for solutions of the problem: xmlhttprequest error flutter
Didn't find the answer?
Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.
Similar questions
Find the answer in similar questions on our website.
Write quick answer
Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.