Where clause in polymorphic relationship

Viewed 124

I have the tables

threads
- id
replies
- id
- repliable_id
- repliable_type

I want to add another column to the Thread, which is the id of the most recent reply.

Thread::where('id',1)->withRecentReply()->get()

And the following query scope

public function scopeWithRecentReply() {
    return $query->addSelect([
            'recent_reply_id' => Reply::select('id')
                ->whereHasMorph('repliable', ['App\Thread'], function ($q) {
                    $q->where('repliable_id', '=', 'threads.id');
                })->latest('created_at')
                ->take(1),
        ]);
}

I have also tried

public function scopeWithRecentReply() {
    return $query->addSelect([
            'recent_reply_id' => Reply::select('id')
                ->where('repliable_id', '=', 'threads.id')
                ->latest('created_at')
                ->take(1),
        ]);
}

But in both cases the

recent_reply_id => null

If instead of threads.id i enter an integer, it works and the recent_reply_id is not null For example

public function scopeWithRecentReply() {
    return $query->addSelect([
            'recent_reply_id' => Reply::select('id')
                ->whereHasMorph('repliable', ['App\Thread'], function ($q) {
                    $q->where('repliable_id', '=', 1);
                })->latest('created_at')
                ->take(1),
        ]);
}

My question is

Is there a way to be able to fetch the recent_reply_id using the respective threads.id ?

1 Answers

I would suggest using appends instead of query scopes so in your Thread model we will add

protected $appends = ['recent_reply_id'];

.....

public function replies () {
    // you need to add here your relation with replies table
}

public function getRecentReplyIdAttribute () {
    return $this->replies()->latest('id')->first()->id;
}

now wherever you query the threads table you will have access to recent_reply_id like

$thread = Thread::where('id',1)->withRecentReply()->get();

$thread->recent_reply_id;
Related