Yii2使用ActiveQuery,在同一个Model上使用子查询

时间:2015-05-15 14:50:59

标签: mysql yii2

我有一个Comments表,其中parent_id个外键指向自身以启用线程注释。

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变量?或者有更好的方法吗?

1 个答案:

答案 0 :(得分:1)

$subQuery = new \yii\db\Query();
$subQuery->select(["max(subQ.created_time)"]);
$subQuery-> from('comments subQ');
$subQuery->where([
    'parent_id' => $parentId
]);

$query = new \yii\db\Query();
$query->select([
    'C.*',
    $subQuery
]);
$query->from('Comments C');
$query->andWhere(
    'parent_id is Null'
);


$command = $query->createCommand();

 /*

   Printing the command will result following sql  with $parentId = 1     

   SELECT
        `C`.*, (
         SELECT
            max(subQ.created_time)
         FROM
            `comments` `subQ`
         WHERE
             `parent_id` =: qp0
         ) AS `1`
    FROM
         `Comments` `C`
    WHERE
         parent_id IS NULL

*/

print_r($command->sql);
  

我不确定ORDER BY last_reply_time DESC;假设last_reply_time是db表属性并且与子查询不同。您可以通过执行$ query-> orderBy('last_reply_time DESC')来简单地在查询中添加orderBy

我希望这会对你有所帮助。欢呼:)