我有一个带有parent_id外键的Comments表,该外键指向自身以启用线程注释.
Comments
id INT UNSIGNED NOT NULL
parent_id INT UNSIGNED NULL
comment TEXT NOT NULL
created_time DATETIME NOT NULL
最初的ActiveQuery就是这样
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]);
}
}
现在我想通过最新的主动回复对评论进行排序.
查询基本上是这样的
SELECT `*`, `last_reply_time`
FROM `Comments`
WHERE `parent_id` IS NULL
ORDER BY `last_reply_time` DESC;
我认为last_reply_time是一个子查询
SELECT MAX(created_time)
FROM `Comments`
WHERE `parent_id` = :something
如何使用上面的CommentActiveQuery构建它.我能得到的最远的是这样的
public function orderByNewestActiveChildCreatedTime() {
return $this->addSelect([
'last_reply_time' => $subQuery
])->orderBy(['last_reply_time' => SORT_DESC]);
}
我应该用什么替换上面的$subQuery变量?或者,还有更好的方法?