public function actionAnswer($id) { $answer = $this->findAnswer($id); $user = Yii::$app->user->getIdentity(); list($result, $like) = Like::Answer($user, $answer); if ($result) { return $this->message('提交成功!', 'success'); } else { return $this->message($like ? $like->getErrors() : '提交失败!'); } }
/** * 喜欢数据切换 * @param User $user * @param ActiveRecord $model * @return array */ protected static function toggleType(User $user, Post $model) { $data = ['target_id' => $model->id, 'target_type' => $model::TYPE, 'author_id' => $user->id, 'status' => static::STATUS_ACTIVE]; if (!static::deleteAll($data + ['type' => static::TYPE])) { // 删除数据有行数则代表有数据,无行数则添加数据 $hate = new static(); $hate->setAttributes($data); $result = $hate->save(); if ($result) { // 如果是新增数据, 删除掉Like的同类型数据 $attributes = ['hate_count' => 1]; if (Like::deleteAll($data + ['type' => Like::TYPE])) { // 如果又删除数据, like_count也要-1 $attributes['like_count'] = -1; } $model->updateCounters($attributes); } return [$result, $hate]; } $model->updateCounters(['hate_count' => -1]); return [true, null]; }
/** * 获取赞记录 * @return mixed */ public function getLike() { return $this->hasOne(Like::className(), ['target_id' => 'id'])->andWhere(['uid' => Yii::$app->user->getId(), 'target_type' => static::TYPE, 'type' => 'like']); }
/** * 获取指定用户的赞记录 * @param null|int $authorId * @return mixed */ public function getLike($authorId = null) { return $this->hasOne(Like::className(), ['target_id' => 'id'])->andWhere(['target_type' => self::TYPE, 'author_id' => $authorId ?: Yii::$app->getUser()->getId()]); }
/** * 获取用户喜欢列表 * @return static */ public function getLikes() { return $this->hasMany(Like::className(), ['author_id' => 'id'])->inverseOf('author'); }