MostofaL's avatar

defining local Scope based on latest relation object

I have a Ticket model and a Reply model.

Every ticket hasMany Replies and each Reply belongsTo one Ticket. I want to define a local scope on the Ticket model and run some conditions on the last reply to that Ticket. for example, If the latest reply Is sent by me, i want to filter out that ticket from the query.

but I'm having a hard time getting the last reply to the ticket on the scope.

for example, I've tried the following:

    public function lastVisibleReply()
    {
        return $this->hasOne(Reply::class, 'ticket_id', 'id')->orderBy('id', 'desc')->where('is_hidden', 0)->latest()->limit(1);
    }
    public function scopeSomeConditionsOnLastReply($query)
    {
        return $query->whereHas('lastVisibleReply', function ($q){
			//some conditions
        })
   }

but the whereHas('lastVisibleReply') just goes over every Reply of the ticket.

when I logged the $query->toSql(), the following was the result:

select * 
from "replies" 
where "tickets"."id" = "replies"."ticket_id" 
// and conditions
and "replies"."deleted_at" is null

as you can see in the log, the "->orderBy('id', 'desc')->where('is_hidden', 0)->latest()->limit(1)" part of the relation definition, was not applied on the whereHas query.

is there a solution?

0 likes
1 reply

Please or to participate in this conversation.