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?
CodePudding user response:
Offer::whereHas('latestMessage', fn($query) => $query->latest('id')->whereNull('read'))->paginate(100);
Remove latest from relation.
CodePudding user response:
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