How can I ensure that my method is only executed once?
P粉198814372
P粉198814372 2024-01-10 17:47:23
0
1
356

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粉198814372
P粉198814372

reply all(1)
P粉373990857

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']
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!