我在模型Users中有一个方法
public function getRating()
{
$id = \Yii::$app->request->get('id');
$rating = Yii::$app->db->createCommand(
"SELECT * FROM (
SELECT *, (@position:=@position+1) as rate FROM (
SELECT executor_id, SUM(rate) / COUNT(rate) as pts FROM user_replies, (SELECT @position:=0) as a
GROUP BY executor_id ORDER BY pts DESC
) AS subselect
) as general WHERE executor_id = $id"
)->queryOne();
return $rating;
}
并且我在视图中输出结果如下
getRating()['rate']; ?>
但是更有经验的开发者告诉我,我的查询会执行两次。有可能重写代码以使其只执行一次吗?
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号
您似乎两次调用了
$singleUser->getRating()。 您可以尝试将结果保存在一个变量中,这样您就不会两次调用数据库。 例如:现在可以直接使用该变量的值。这样可以避免再次访问数据库。