I have a Comments table that have parent_id foreign key that points to itself to enable threaded comment.
Comments
id INT UNSIGNED NOT NULL
parent_id INT UNSIGNED NULL
comment TEXT NOT NULL
created_time DATETIME NOT NULL
The original ActiveQuery is like this
class CommentActiveQuery extends \yii\db\ActiveQuery {
public function andWhereIsNotRemoved() {
return $this->andWhere(['isRemoved' => Comment::STATUS_IS_NOT_REMOVED]);
}
public function andWhereParentIdIs($parentId) {
return $this->andWhere(['parentId' => $parentId]);
}
public function orderByNewestCreatedTime() {
return $this->orderBy(['createdTime' => SORT_DESC]);
}
}
Now I want to sort the comments by the newest active reply.
The query is basically like this
SELECT `*`, `last_reply_time`
FROM `Comments`
WHERE `parent_id` IS NULL
ORDER BY `last_reply_time` DESC;
I'm thinking the last_reply_time is a subquery
SELECT MAX(created_time)
FROM `Comments`
WHERE `parent_id` = :something
How to build this using the CommentActiveQuery above. The farthest I can get is like this
public function orderByNewestActiveChildCreatedTime() {
return $this->addSelect([
'last_reply_time' => $subQuery
])->orderBy(['last_reply_time' => SORT_DESC]);
}
With what should I replace the $subQuery variable above? Or is there a better way?