2

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 ?

Orestis uRic
  • 347
  • 1
  • 6
  • 11

1 Answers1

0

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;
mmabdelgawad
  • 2,385
  • 2
  • 7
  • 15
  • Actually, i need the id in the query scope because i want to continue building the query, because the query i want to create is a little bit more complex than just fetching the id. – Orestis uRic Jul 17 '20 at 17:58