0

I have a Posts table and polymorphic relation of Comments table.

What I tried (not sure if it is the right way to go) but I get a message that column last_activity does not exist

class Post extends Eloquent {

...    

$appends = ['last_activity'];

public function getLastActivityAttribute()
        {
            if($this->has('comments', '>', 0))
            {
                $comment = $this->comments()->getQuery()->orderBy('created_at', 'desc')->first();
                return $comment->created_at;
            }
            else
            {
                return '1970-01-01 00:00:00';
            }
        }

...

}

So basically:

I want posts ordered by the created_at field of the comment

with Eloquent. I saw this, but it looks like he sorts the comments instead of the posts.

Help?

Community
  • 1
  • 1
Glad To Help
  • 5,299
  • 4
  • 38
  • 56

2 Answers2

0

Ret changing your line to

$this->attributes['last_activity'];

This should retrieve the current last activity when your are calling your model

Jazerix
  • 4,729
  • 10
  • 39
  • 71
0

Making this type of calculation has proved to be very resource-inefficient and performed poorly.

Therefore I ended up adding a new database field called last_activity and then, with the help of Laravel Events, I attached listeners to update the last_activity field.

By doing this I avoided the need to perform a complex query against the database.

Glad To Help
  • 5,299
  • 4
  • 38
  • 56