gpt4 book ai didi

mysql - Yii2 使用在同一模型上使用子查询的 ActiveQuery

转载 作者:可可西里 更新时间:2023-11-01 07:39:22 24 4
gpt4 key购买 nike

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

最佳答案

$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);

I am not sure about ORDER BY last_reply_time DESC; Assuming last_reply_time is db table attribute and is different from the subquery. You can simply add orderBy in the query by doing $query->orderBy('last_reply_time DESC')

希望这对您有所帮助。干杯:)

关于mysql - Yii2 使用在同一模型上使用子查询的 ActiveQuery,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30262572/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com