简体   繁体   English

Laravel按最新评论的日期对帖子进行排序

[英]Laravel Sort Posts by the date of the newest comment

I have a Posts table and polymorphic relation of Comments table. 我有一个Posts表和Comments表的多态关系。

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 我尝试了什么(不确定是否是正确的方法),但是我收到一条消息,指出last_activity列不存在

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 我要按评论的created_at字段排序的帖子

with Eloquent. 与口才。 I saw this , but it looks like he sorts the comments instead of the posts. 我看到 ,但是看起来他对评论进行了排序而不是帖子。

Help? 救命?

Ret changing your line to 不要将您的行更改为

$this->attributes['last_activity']; $ this-> attributes ['last_activity'];

This should retrieve the current last activity when your are calling your model 当您调用模型时,这应该检索当前的上一个活动

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. 因此,我最终添加了一个名为last_activity的新数据库字段,然后在Laravel Events的帮助下,我附加了侦听器以更新last_activity字段。

By doing this I avoided the need to perform a complex query against the database. 通过这样做,我避免了对数据库执行复杂查询的需要。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM