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 i output result in the view like that <?php echo $singleUser->getRating()['rate']; ?>
but more qualified coder said me that my query will be executing 2 times. Is that possible to rewrite code so it executes only 1 time?
CodePudding user response:
You seem to be calling $singleUser->getRating()
twice.
You could try saving the result in a variable, that way you will not call the database twice.
i.e.
$rating = $singleUser->getRating();
Now it's possible to just use the value from that variable. Saving you a trip to the database.
!is_null($rating)
echo $rating['rate']
CodePudding user response:
As mentioned by thordoor, you can save the value to a variable.
I would just like to add that you could use a private static variable inside the class.
private static $_rating;
And inside your Method you could look inside this variable.
public function getRating(){
if(static::$_rating===null){
// here goes your code
// and an asignment like
static::$_rating = $rating;
}
return static::$_rating;
}
With this way you can have multiple user objects and query the ratings for each of them.
Correct me if I am wrong.