Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

Nael.Saeed's avatar

OrderBy a relationship column of a relationship

Hi guys, I am facing a problem in here. I have 3 tables posts, threads and comments. a thread contain comments and is attached to a post. So, there is a relation between post and threads and a relation between threads and comments. What I need is to sort posts by the latest where if a post has a thread that contains comments then use the comment created_at else if post has no thread attached then use post created at. so I kind of need order by if exists thread.comments.created_at else post.created_at

is this possible?

0 likes
1 reply
MaverickChan's avatar

in any model


public function relationship () {

    return $this->hasMany(Model::class)->orderBy('anything')    ;
    
}


it can be chained.

Please or to participate in this conversation.