Reputation: 5111
I have two tables: offers
and messages
. offers
can have several messages
. This is the relation code:
public function latestMessage()
{
return $this->hasOne(Message::class, 'seller_id', 'seller_id')->latest();
}
I want to get only the offers
whose latest message must not have been read.
Offer::whereHas('latestMessage', fn($query) => $query->whereNull('read'))->paginate(100);
But the whereHas
just checks if any of the record is not read instead of checking the latest one. How do I make sure whereHas
always checks the latest record?
Upvotes: 0
Views: 106
Reputation: 5111
Adding ->latestOfMany()
works.
public function latestMessage()
{
return $this->hasOne(Message::class, 'seller_id', 'seller_id')->latestOfMany();
}
Upvotes: 0
Reputation: 298
You can change your relation class as below
if your relation is hasMany then use below function
public function latestMessage(){
return $this->hasMany(Message::class, 'seller_id', 'seller_id')->whereNull('read')->orderByDesc('created_at');
}
if your relation is hasOne then use below function
public function latestMessage(){
return $this->hasOne(Message::class, 'seller_id', 'seller_id')->whereNull('read')->latestOfMany();
}
please try this and let us know if its working or not
Upvotes: 0
Reputation: 379
Offer::whereHas('latestMessage', fn($query) => $query->latest('id')->whereNull('read'))->paginate(100);
Remove latest from relation.
Upvotes: 0