Yii2 using ActiveQuery, which uses a subquery on the same model

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?

+4
source share
1 answer
$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 . orderBy , $query- > orderBy ('last_reply_time DESC')

, . :)

+1

All Articles