course/app/common/service/FavoriteService.php

128 lines
3.5 KiB
PHP
Raw Normal View History

<?php
namespace app\common\service;
use app\common\model\Favorite;
use app\constant\ResponseCode;
use support\Redis;
use think\Exception;
class FavoriteService
{
/**
* @desc 收藏
* @param $request
* @return array
*/
public function add($request)
{
try {
$data = $request->post();
$redis_key = 'favorite_' . $request->user->id . '-' . $data['photographer_id'];
if (Redis::get($redis_key)) {
throw new Exception('不能操作太频繁哟~');
}
Redis::setEx($redis_key, 5, 1);
$favorite = Favorite::where(['user_id' => $request->user->id, 'photographer_id' => $data['photographer_id']])->findOrEmpty();
if (!$favorite->isEmpty()) {
throw new Exception('您已收藏了该摄影师,不能重复收藏哟~');
}
$res = Favorite::create([
'user_id' => $request->user->id,
'photographer_id' => $data['photographer_id']
]);
if (!$res) {
throw new Exception('收藏失败');
}
return [
'code' => ResponseCode::SUCCESS,
'msg' => '收藏成功'
];
} catch (Exception $e) {
return [
'code' => ResponseCode::FAIL,
'msg' => $e->getMessage()
];
}
}
/**
* @desc 取消收藏
* @param $request
* @return array
*/
public function cancel($request)
{
try {
$data = $request->post();
$redis_key = 'favorite_' . $request->user->id . '-' . $data['photographer_id'];
if (Redis::get($redis_key)) {
throw new Exception('不能操作太频繁哟~');
}
Redis::setEx($redis_key, 5, 1);
$favorite = Favorite::where(['user_id' => $request->user->id, 'photographer_id' => $data['photographer_id']])->findOrEmpty();
if ($favorite->isEmpty()) {
throw new Exception('您未收藏该摄影师');
}
$res = $favorite->delete();
if (!$res) {
throw new Exception('取消收藏失败');
}
return [
'code' => ResponseCode::SUCCESS,
'msg' => '取消成功'
];
} catch (Exception $e) {
return [
'code' => ResponseCode::FAIL,
'msg' => $e->getMessage()
];
}
}
/**
* @desc 收藏列表
* @param $request
* @return array
*/
public function getFavoriteList($request)
{
try {
$data = $request->get();
$favorite = Favorite::order('id desc')->where(['user_id' => $request->user->id]);
$page = isset($data['page']) ? $data['page'] : 1;
$limit = isset($data['limit']) ? $data['limit'] : 10;
$total = $favorite->count();
$list = $favorite->with(['photographer'])->page($page, $limit)->select();
return [
'code' => ResponseCode::SUCCESS,
'data' => [
'list' => $list,
'total' => $total,
'page' => $page
]
];
} catch (Exception $e) {
return [
'code' => ResponseCode::FAIL,
'msg' => $e->getMessage()
];
}
}
}