I have a method in the model 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; }
And my output results in the view are as follows
getRating()['rate']; ?>
But more experienced developers told me that my query would be executed twice. Is it possible to rewrite the code so that it only executes once?
P粉3739908572024-01-11 09:04:01
You appear to be calling $singleUser->getRating()
twice.
You could try saving the results in a variable so you don't call the database twice.
For example:
$rating = $singleUser->getRating();
The value of this variable can now be used directly. This avoids accessing the database again.
!is_null($rating) echo $rating['rate']