/** * Выставление оценки для статьи * * @return string * @throws \Exception */ public function actionRating() { $message = ''; if ((Yii::$app->request->get('score') == 1 || Yii::$app->request->get('score') == -1) && Yii::$app->request->get('post_id')) { $postId = Yii::$app->request->get('post_id'); $score = Yii::$app->request->get('score'); if (!Yii::$app->user->isGuest) { $rating = new PostsRating(); $rating->post_id = $postId; $rating->user_id = Yii::$app->user->identity->getId(); $rating->score = $score; try { if ($rating->save()) { $message = 'Спасибо! Ваш голос засчитан'; } else { $err = $rating->errors; $message = current($err)[0]; } } catch (IntegrityException $e) { if (strpos($e->errorInfo[2], 'foreign key')) { $message = 'Ошибка. Неверный ID статьи'; } } } else { $message = 'Голосовать могут только зарегистрированные пользователи'; } } else { return 'Ошибка'; } return RatingWidget::widget(['post_id' => $postId, 'message' => $message]); }
/** * @inheritdoc */ public function run() { if (!$this->post_id) { return ''; } $ratings = PostsRating::find()->where(['post_id' => $this->post_id])->asArray()->all(); // Подсчитываем общую сумму и количество плюсов и минусов $rating['score'] = 0; $rating['numPlus'] = 0; $rating['numMinus'] = 0; $rating['votes'] = count($ratings); foreach ($ratings as $rate) { $rating['score'] += $rate['score']; if ($rate['score'] == '1') { $rating['numPlus']++; } elseif ($rate['score'] == '-1') { $rating['numMinus']++; } } if ($rating['score'] > 0) { $rating['score'] = '+' . $rating['score']; } $rating['scoreClass'] = $rating['score'] > 0 ? 'positive' : ($rating['score'] == 0 ? 'null' : 'negative'); return $this->render('rating', ['rating' => $rating, 'message' => $this->message]); }
/** * Возвращает рейтинг статьи (сумму выставленных плюсов и минусов) * @return integer */ public function getPostsRating() { $rates = $this->hasMany(PostsRating::className(), ['post_id' => 'id'])->sum('score'); return $rates; }