/** * 收藏或取消收藏 * @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; }