123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111 |
- <?php
- declare (strict_types=1);
- namespace app\api\controller;
- use app\api\service\User as UserService;
- use app\common\model\UserFavorite as UserFavoriteModel;
- use app\common\model\Goods as GoodsModel;
- /**
- * 收藏表
- * Class User
- * @package app\api
- */
- class Favorites extends Controller
- {
- /**
- * Notes:添加收藏
- * Author: zhangs
- * DateTime: 2021/9/25 11:00
- * @param $target_type
- * @param $target_id
- * @return mixed
- */
- public function add($target_type, int $target_id)
- {
- $userinfo = UserService::getCurrentLoginUser(true);
- $ufModel = new UserFavoriteModel;
- $one = $ufModel->getOne($userinfo->user_id, $target_type, $target_id);
- if (empty($one)) {
- $this->setInc($ufModel, $userinfo->user_id, $target_type, $target_id);
- return $this->renderSuccess([], '收藏成功');
- } else {
- $this->setDec($ufModel, $userinfo->user_id, $target_type, $target_id);
- return $this->renderSuccess([], '取消收藏成功');
- }
- }
- /**
- * Notes:取消收藏
- * Author: zhangs
- * DateTime: 2021/9/25 11:00
- * @param $target_type
- * @param $target_id
- * @return mixed
- */
- public function cancel($target_type, int $target_id)
- {
- $userinfo = UserService::getCurrentLoginUser(true);
- $ufModel = new UserFavoriteModel;
- $one = $ufModel->getOne($userinfo->user_id, $target_type, $target_id);
- if ($one) {
- $this->setDec($ufModel, $userinfo->user_id, $target_type, $target_id);
- return $this->renderSuccess([], '取消收藏成功');
- }
- return $this->renderError('取消收藏失败');
- }
- //自增
- protected function setInc($ufModel, $user_id, $target_type, $target_id)
- {
- $ufModel->addOne($user_id, $target_type, $target_id);
- switch ($target_type) {
- case 1: //商品收藏
- GoodsModel::setIncByField($target_id, 'collect_num', 1);
- break;
- }
- }
- //自减
- protected function setDec($ufModel, $user_id, $target_type, $target_id)
- {
- $ufModel->deleteOne($user_id, $target_type, $target_id);
- switch ($target_type) {
- case 1: //商品收藏
- GoodsModel::setDecByField($target_id, 'collect_num', 1);
- break;
- }
- }
- /**
- * Notes:收藏列表
- * Author: zhangs
- * DateTime: 2021/9/25 11:00
- * @param int $target_type
- * @return mixed
- */
- public function list($target_type = 1)
- {
- $ufModel = new UserFavoriteModel;
- $userinfo = UserService::getCurrentLoginUser(true);
- $listFavorite = $ufModel->getList(intval($userinfo->user_id), $target_type)->toArray();
- $ids = array_column($listFavorite['data'], 'target_id');
- if ($target_type == 1) { //收藏的商品
- $array = (new GoodsModel)->getListByIds($ids, false);
- foreach ($listFavorite['data'] as &$row) {
- foreach ($array as $key => $arr) {
- if ($row['target_id'] == $arr['goods_id']) {
- $row['detail'] = $array[$key];
- }
- }
- }
- }
- $list = $listFavorite;
- return $this->renderSuccess(compact('list'));
- }
- }
|