123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108 |
- <?php
- /**
- * Created by PhpStorm.
- * User: Administrator
- * Date: 2019-06-10
- * Time: 18:12
- */
- namespace App\Repositories;
- use App\Models\Category;
- use App\Models\CategoryTopic;
- use App\Models\Topic;
- use Dingo\Api\Http\Response;
- use Illuminate\Support\Facades\DB;
- use Illuminate\Database\QueryException;
- class TopicRepository {
- public function __construct(Topic $topic,CategoryTopic $categoryTopic){
- $this->topic = $topic;
- $this->categoryTopic = $categoryTopic;
- }
- //列表
- public function index($request){
- $perPage = isset($request['per_page']) ? $request['per_page'] : 20;
- $where = [];
- if(isset($request['name'])){
- $where[] = ['name', 'like', "%{$request['name']}%"];
- }
- return $this->topic->where($where)->paginate($perPage);
- }
- public function create($request){
- $topic = $this->topic->where(['name'=>$request['name']])->first();
- if($topic){
- return Response::create([
- 'message' => '该话题已存在',
- 'status_code' => 500
- ]);
- }
- $data = [
- 'name' => $request['name'],
- 'img' => $request['img'],
- 'desc' => $request['desc'],
- ];
- if(isset($request['category_ids'])){
- $category_ids = explode(',', $request['category_ids']);
- }
- DB::beginTransaction();
- try{
- $topicInfo = $this->topic->create($data);
- if($topicInfo){
- if($category_ids){
- $category_topic_data = [];
- foreach($category_ids as $value){
- $category_topic_data[] = [
- 'category_id' => $value,
- 'topic_id' => $topicInfo->id,
- ];
- }
- $this->categoryTopic->insert($category_topic_data);
- }
- }
- DB::commit();
- return Response::create();
- }catch (QueryException $exception){
- DB::rollBack();
- Log::debug('新增话题:'.$exception->getMessage());
- return Response::create([
- 'message' => '新增话题,请重试',
- 'error' => $exception->getMessage(),
- 'status_code' => 500
- ]);
- }
- }
- //修改
- public function update($request){
- $topic = $this->topic->where('id', $request['id'])->first();
- if(!$topic){
- return Response::create([
- 'message' => '该话题不存在',
- 'status_code' => 500
- ]);
- }
- if(isset($request['is_open']) && $request['is_open'] !== null){
- $topic->is_open = $request['is_open'];
- }
- if($request['type']){
- if($topic->is_open == 0){
- return Response::create([
- 'message' => '该话题未开启',
- 'status_code' => 500
- ]);
- }
- if(isset($request['type']) == 1){
- $topic->is_suggest = $request['is_suggest'];
- }
- if(isset($request['type']) == 2){
- $topic->is_hot = $request['is_hot'];
- }
- }
- $res = $topic->save();
- if($res){
- return Response::create();
- }
- }
- }
|