public function actionQuestion($id)
 {
     $question = $this->findQuestion($id);
     $user = Yii::$app->user->getIdentity();
     list($result, $like) = Favorite::Question($user, $question);
     if ($result) {
         return $this->message('提交成功!', 'success');
     } else {
         return $this->message($like ? $like->getErrors() : '提交失败!');
     }
 }
Exemple #2
0
 /**
  * 获取指定用户的收藏记录
  * @param null|int $authorId
  * @return mixed
  */
 public function getFavorite($authorId = null)
 {
     return $this->hasOne(Favorite::className(), ['target_id' => 'id'])->andWhere(['target_type' => self::TYPE, 'author_id' => $authorId ?: Yii::$app->getUser()->getId()]);
 }
Exemple #3
0
 /**
  * 收藏或取消收藏
  * @param $uid
  * @return bool|string  string为错误提示, bool为操作成功还是失败
  */
 public function toggleFavorite($uid)
 {
     $params = ['uid' => $uid, 'target_id' => $this->id, 'target_type' => static::TYPE];
     $favorite = Favorite::findOne($params);
     $active = true;
     if ($favorite) {
         // 已经收藏了则取消收藏
         $active = false;
         $return = $favorite->delete() >= 0;
     } else {
         $favorite = new Favorite();
         $favorite->setAttributes($params);
         $return = $favorite->save() ?: array_values($favorite->getFirstErrors())[0];
     }
     if ($return == true) {
         // 更新记数
         $this->updateCounters(['favorite_count' => $active ? 1 : -1]);
     }
     return $return;
 }