I have a table Commentsthat has a parent_idforeign key that points to itself to enable a comment stream.
Comments
id INT UNSIGNED NOT NULL
parent_id INT UNSIGNED NULL
comment TEXT NOT NULL
created_time DATETIME NOT NULL
The original is ActiveQueryas follows
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 last active answer.
The request is mostly similar to this
SELECT `*`, `last_reply_time`
FROM `Comments`
WHERE `parent_id` IS NULL
ORDER BY `last_reply_time` DESC;
I think that last_reply_timeis a subquery
SELECT MAX(created_time)
FROM `Comments`
WHERE `parent_id` = :something
How to build it using the CommentActiveQueryabove. The farthest thing I can get is like this
public function orderByNewestActiveChildCreatedTime() {
return $this->addSelect([
'last_reply_time' => $subQuery
])->orderBy(['last_reply_time' => SORT_DESC]);
}
What should replace the variable $subQueryabove? Or is there a better way?
source
share