Home  >  Q&A  >  body text

How can I ensure that my method is only executed once?

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粉198814372P粉198814372257 days ago327

reply all(1)I'll reply

  • P粉373990857

    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']

    reply
    0
  • Cancelreply