Преглед изворни кода

Merge remote-tracking branch 'origin/develop' into develop

wzq пре 5 година
родитељ
комит
c4c45069a6

+ 143 - 0
app/Console/Commands/PostStatistics.php

@@ -0,0 +1,143 @@
+<?php
+/**
+ * Created by PhpStorm.
+ * User: Administrator
+ * Date: 2019/6/12
+ * Time: 16:32
+ */
+
+namespace App\Console\Commands;
+
+
+use App\Models\Behavior;
+use App\Models\CommentRecord;
+use App\Models\GeneralRecord;
+use App\Models\PostLog;
+use App\Models\ReleaseRecord;
+use Illuminate\Console\Command;
+use Illuminate\Support\Carbon;
+use Illuminate\Support\Facades\DB;
+use Illuminate\Support\Facades\Log;
+use Illuminate\Support\Facades\Redis;
+
+class PostStatistics extends Command
+{
+    /**
+     * The name and signature of the console command.
+     *
+     * @var string
+     */
+    protected $signature = 'post:statistics';
+
+    /**
+     * The console command description.
+     *
+     * @var string
+     */
+    protected $description = '全部内容统计';
+
+    /**
+     * Create a new command instance.
+     *
+     * @return void
+     */
+    public function __construct(\App\Models\PostStatistics $postStatistics,
+                                GeneralRecord $generalRecord,
+                                ReleaseRecord $releaseRecord,
+                                CommentRecord $commentRecord,
+                                PostLog $postLog,
+                                Behavior $behavior)
+    {
+        parent::__construct();
+        $this->postStatistics = $postStatistics;
+        $this->generalRecord = $generalRecord;
+        $this->releaseRecord = $releaseRecord;
+        $this->commentRecord = $commentRecord;
+        $this->postLog = $postLog;
+        $this->behavior = $behavior;
+    }
+
+    /**
+     * Execute the console command.
+     *
+     * @return mixed
+     */
+    public function handle()
+    {
+        $this->line("开始统计所有内容");
+        $yesterdayStart = Carbon::yesterday()->startOfDay()->toDateTimeString();
+        $yesterdayEnd = Carbon::yesterday()->endOfDay()->toDateTimeString();
+        $post = $this->releaseRecord
+            ->where([['created_at', '>=', $yesterdayStart], ['created_at', '<=', $yesterdayEnd]])
+            ->select(DB::raw('count(*) as post_count'))
+            ->first();
+        $comment = $this->commentRecord
+            ->where([['created_at', '>=', $yesterdayStart], ['created_at', '<=', $yesterdayEnd]])
+            ->select(DB::raw('count(*) as comment_count'))
+            ->first();
+        $behaviors = $this->behavior->whereIn('behavior_identification', ['read', 'like', 'share', 'collect'])->get()->toArray();
+        $postCount = $post->post_count;
+        $commentCount = $comment->comment_count;
+        $readCount = 0;
+        $likeCount = 0;
+        $shareCount = 0;
+        $collectCount = 0;
+        foreach ($behaviors as $behavior) {
+            $behaviorId = $behavior['virus_behavior_id'];
+            if ($behavior['behavior_identification'] == 'read') {
+                $read = $this->generalRecord
+                    ->where([['created_at', '>=', $yesterdayStart], ['created_at', '<=', $yesterdayEnd], ['virus_behavior_id', $behaviorId]])
+                    ->select(DB::raw('count(*) as read_count'))
+                    ->first();
+                $readCount = $read->read_count;
+            } elseif ($behavior['behavior_identification'] == 'like') {
+                $like = $this->generalRecord
+                    ->where([['created_at', '>=', $yesterdayStart], ['created_at', '<=', $yesterdayEnd], ['virus_behavior_id', $behaviorId]])
+                    ->select(DB::raw('count(*) as like_count'))
+                    ->first();
+                $likeCount = $like->like_count;
+            } elseif ($behavior['behavior_identification'] == 'share') {
+                $share = $this->generalRecord
+                    ->where([['created_at', '>=', $yesterdayStart], ['created_at', '<=', $yesterdayEnd], ['virus_behavior_id', $behaviorId]])
+                    ->select(DB::raw('count(*) as share_count'))
+                    ->first();
+                $shareCount = $share->share_count;
+            } elseif ($behavior['behavior_identification'] == 'collect') {
+                $collect = $this->generalRecord
+                    ->where([['created_at', '>=', $yesterdayStart], ['created_at', '<=', $yesterdayEnd], ['virus_behavior_id', $behaviorId]])
+                    ->select(DB::raw('count(*) as collect_count'))
+                    ->first();
+                $collectCount = $collect->collect_count;
+            }
+        }
+        Log::info(date('Y-m-d H:i:s').'统计'.$yesterdayStart.',帖子数:'.$postCount.'评论数:'.$commentCount.'阅读数:'.$readCount.'点赞数:'.$likeCount.'收藏数:'.$collectCount.'分享数:'.$shareCount);
+        $postLog = $this->postLog
+            ->where([['created_at', '>=', $yesterdayStart], ['created_at', '<=', $yesterdayEnd]])
+            ->select('content')
+            ->get()->toArray();
+        foreach ($postLog as $log){
+            $logContent = json_decode($log['content'],true);
+            if(isset($logContent['add_pv']) && $logContent['add_pv']){
+                $readCount -= $logContent['add_pv'];
+            }
+            if(isset($logContent['add_praise_count']) && $logContent['add_praise_count']){
+                $likeCount -= $logContent['add_praise_count'];
+            }
+            if(isset($logContent['add_collect_count']) && $logContent['add_collect_count']){
+                $collectCount -= $logContent['add_collect_count'];
+            }
+            if(isset($logContent['add_collect_count']) && $logContent['add_collect_count']){
+                $shareCount -= $logContent['add_collect_count'];
+            }
+            Log::debug(date('Y-m-d H:i:s').'统计虚拟数'.$yesterdayStart.',阅读数:'.$logContent['add_pv'].'点赞数:'.$logContent['add_praise_count'].'收藏数:'.$logContent['add_collect_count'].'分享数:'.$logContent['add_collect_count']);
+        }
+        $data['post_count'] = $postCount;
+        $data['read_count'] = $readCount;
+        $data['share_count'] = $shareCount;
+        $data['like_count'] = $likeCount;
+        $data['collect_count'] = $collectCount;
+        $data['comment_count'] = $commentCount;
+        $this->postStatistics->create($data);
+        Log::info(date('Y-m-d H:i:s').'统计'.$yesterdayStart.'最终记录数据:'.json_encode($data));
+    }
+}

+ 2 - 1
app/Console/Commands/PostYesterday.php

@@ -53,7 +53,8 @@ class PostYesterday extends Command
         $this->line("开始统计昨日内容");
 
         $postData = $this->postData
-            ->where('created_at', '>=', Carbon::now()->startOfDay()->toDateTimeString())
+            ->where('created_at', '>=', Carbon::yesterday()->startOfDay()->toDateTimeString())
+            ->where('created_at', '<=', Carbon::yesterday()->endOfDay()->toDateTimeString())
             ->select(DB::raw('count(*) as count'), DB::raw('sum(create_bean) as bean'))
             ->first();
         Log::info('统计昨日内容'.json_encode($postData));

+ 7 - 2
app/Console/Kernel.php

@@ -4,6 +4,7 @@ namespace App\Console;
 
 use App\Console\Commands\Apollo;
 use App\Console\Commands\Downloads;
+use App\Console\Commands\PostStatistics;
 use App\Console\Commands\PostYesterday;
 use Illuminate\Console\Scheduling\Schedule;
 use Laravel\Lumen\Console\Kernel as ConsoleKernel;
@@ -18,7 +19,8 @@ class Kernel extends ConsoleKernel
     protected $commands = [
         Apollo::class,
         PostYesterday::class,
-        Downloads::class
+        Downloads::class,
+        PostStatistics::class
     ];
 
     /**
@@ -36,7 +38,10 @@ class Kernel extends ConsoleKernel
             ->withoutOverlapping()->appendOutputTo($path);
 
         $schedule->command('post:yesterday')
-            ->dailyAt('23:50')
+            ->dailyAt('00:10')
+            ->withoutOverlapping()->appendOutputTo($path);
+        $schedule->command('post:statistics')
+            ->dailyAt('00:20')
             ->withoutOverlapping()->appendOutputTo($path);
     }
 }

+ 7 - 0
app/Http/Controllers/Post/PostController.php

@@ -13,6 +13,7 @@ use App\Transformers\Post\CommentTransformer;
 use App\Transformers\Post\DetailTransformer;
 use App\Transformers\Post\LogTransformer;
 use App\Transformers\Post\PostTransformer;
+use Carbon\Carbon;
 use Illuminate\Http\Request;
 use Illuminate\Support\Facades\Validator;
 use App\Http\Controllers\Controller;
@@ -307,4 +308,10 @@ class PostController extends Controller
         return $data;
     }
 
+    public function statistics(Request $request){
+        $request = $request->all();
+        $start = Carbon::parse(!empty($request['start']) ? Carbon::parse($request['start'])->startOfDay()->toDateTimeString() : Carbon::yesterday())->startOfDay()->toDateTimeString();
+        $end = Carbon::parse(!empty($request['end']) ? Carbon::parse($request['end'])->endOfDay()->toDateTimeString() : Carbon::yesterday())->endOfDay()->toDateTimeString();
+        return $this->postRepository->statistics($start,$end);
+    }
 }

+ 17 - 0
app/Models/PostStatistics.php

@@ -0,0 +1,17 @@
+<?php
+/**
+ * Created by PhpStorm.
+ * User: Administrator
+ * Date: 2019/6/6
+ * Time: 11:21
+ */
+
+namespace App\Models;
+use Illuminate\Database\Eloquent\Model;
+
+class PostStatistics extends Model
+{
+//
+    protected $table = 'community_statistics';
+    protected $guarded = [];
+}

+ 99 - 108
app/Repositories/Behavior/BehaviorRepository.php

@@ -4,10 +4,12 @@ use App\Models\Behavior;
 use App\Models\BehaviorOperationLog;
 use App\Models\CommentRecord;
 use App\Models\GeneralRecord;
+use App\Models\Post;
 use App\Models\RegisteredRecord;
 use App\Models\ReleaseRecord;
 use GuzzleHttp\Client;
 use GuzzleHttp\Exception\RequestException;
+use Illuminate\Support\Carbon;
 use Illuminate\Support\Facades\DB;
 use Illuminate\Support\Facades\Log;
 use Tymon\JWTAuth\Facades\JWTAuth;
@@ -24,9 +26,9 @@ use Illuminate\Database\QueryException;
 
 class BehaviorRepository
 {
-    public function __construct(Behavior $behavior,BehaviorOperationLog $behaviorOperationLog,
-                                RegisteredRecord $registeredRecord,CommentRecord $commentRecord,
-                                GeneralRecord $generalRecord,ReleaseRecord $releaseRecord)
+    public function __construct(Behavior $behavior, BehaviorOperationLog $behaviorOperationLog,
+                                RegisteredRecord $registeredRecord, CommentRecord $commentRecord,
+                                GeneralRecord $generalRecord, ReleaseRecord $releaseRecord)
     {
         $this->behavior = $behavior;
         $this->behaviorOperationLog = $behaviorOperationLog;
@@ -60,53 +62,53 @@ class BehaviorRepository
             ]);
             $res = json_decode($response->getBody()->getContents(), true);
             $res = $res ? $res['behaviors'] : [];
-        }catch (RequestException $exception){
+        } catch (RequestException $exception) {
             $res = [
                 'returnCode' => '-1',
-                'errMsg' => '网络超时'.$exception->getMessage()
+                'errMsg' => '网络超时' . $exception->getMessage()
             ];
-            Log::debug('获取virus行为列表:'.$exception->getMessage());
+            Log::debug('获取virus行为列表:' . $exception->getMessage());
         }
         //已登记行为
         $registered_bahavior = $this->behavior->get();
         $registered_bahaviors = $registered_bahavior->toArray();
 
-        foreach ($registered_bahaviors as $key=>$val){
+        foreach ($registered_bahaviors as $key => $val) {
             $registered_bahaviors[$key]['behavior_status'] = 1;//已登记
         }
-        $virus_behavior_id = array_column($registered_bahaviors,'virus_behavior_id');
+        $virus_behavior_id = array_column($registered_bahaviors, 'virus_behavior_id');
 
         $new_res = [];
         //行为列表去重
-        foreach ($res as $k=>$v) {
-            if (isset($v['_id']) && !empty($virus_behavior_id)){
-                    $res[$k]['behavior_status'] = 0;//未登记
-                    $res[$k]['behavior_flag'] = $v['behavior_flag'];
-                    $res[$k]['behavior_identification'] = $v['behavior_flag'];
-                    unset($res[$k]['behavior_flag']);
+        foreach ($res as $k => $v) {
+            if (isset($v['_id']) && !empty($virus_behavior_id)) {
+                $res[$k]['behavior_status'] = 0;//未登记
+                $res[$k]['behavior_flag'] = $v['behavior_flag'];
+                $res[$k]['behavior_identification'] = $v['behavior_flag'];
+                unset($res[$k]['behavior_flag']);
                 if (in_array($v['_id'], $virus_behavior_id)) {
                     unset($res[$k]);
                 }
-                    $new_res = array_merge($res, $registered_bahaviors);
+                $new_res = array_merge($res, $registered_bahaviors);
 
-            }elseif (!isset($v['_id']) && $virus_behavior_id) {
-                    $new_res = $registered_bahaviors;
-            }elseif (isset($v['_id']) && empty($virus_behavior_id)){
-                    $res[$k]['behavior_status'] = 0;//未登记
-                    $res[$k]['behavior_flag'] = $v['behavior_flag'];
-                    $res[$k]['behavior_identification'] = $v['behavior_flag'];
-                    unset($res[$k]['behavior_flag']);
-                    $new_res = $res;
+            } elseif (!isset($v['_id']) && $virus_behavior_id) {
+                $new_res = $registered_bahaviors;
+            } elseif (isset($v['_id']) && empty($virus_behavior_id)) {
+                $res[$k]['behavior_status'] = 0;//未登记
+                $res[$k]['behavior_flag'] = $v['behavior_flag'];
+                $res[$k]['behavior_identification'] = $v['behavior_flag'];
+                unset($res[$k]['behavior_flag']);
+                $new_res = $res;
             }
         }
         $new_re = [];
         //根据行为ID筛选
-        if (isset($request['virus_behavior_id'])){
-            foreach ($new_res as $k=>$v){
-                if (isset($v['id']) && $v['id'] != $request['virus_behavior_id']){
+        if (isset($request['virus_behavior_id'])) {
+            foreach ($new_res as $k => $v) {
+                if (isset($v['id']) && $v['id'] != $request['virus_behavior_id']) {
                     unset($new_res[$k]);
                     $new_re = array_merge($new_res);
-                }elseif (isset($v['_id']) && $v['_id'] != $request['virus_behavior_id']){
+                } elseif (isset($v['_id']) && $v['_id'] != $request['virus_behavior_id']) {
                     unset($new_res[$k]);
                     $new_re = array_merge($new_res);
                 }
@@ -114,9 +116,9 @@ class BehaviorRepository
             return $new_re;
         }
         //根据行为状态(类型)筛选
-        if (isset($request['behavior_status'])){
-            foreach ($new_res as $kk=>$vv){
-                if (isset($vv['behavior_status']) && $vv['behavior_status'] != $request['behavior_status']){
+        if (isset($request['behavior_status'])) {
+            foreach ($new_res as $kk => $vv) {
+                if (isset($vv['behavior_status']) && $vv['behavior_status'] != $request['behavior_status']) {
                     unset($new_res[$kk]);
                     $new_re = array_merge($new_res);
                 }
@@ -137,12 +139,12 @@ class BehaviorRepository
 //            return $new_re;
 //        }
         //根据行为名称筛选
-        if (isset($request['name'])){
+        if (isset($request['name'])) {
             foreach ($new_res as $key => $val) {
-                if (isset($val['name']) && strpos($val['name'],$request['name']) !== false) {
+                if (isset($val['name']) && strpos($val['name'], $request['name']) !== false) {
                     $new_re[] = $new_res[$key];
                 }
-                if (isset($val['behavior_name']) && strpos($val['behavior_name'],$request['name']) !== false ) {
+                if (isset($val['behavior_name']) && strpos($val['behavior_name'], $request['name']) !== false) {
                     $new_re[] = $new_res[$key];
                 }
             }
@@ -158,20 +160,20 @@ class BehaviorRepository
             throw new HttpException(500, '该行为已存在');
         }
 
-        if(isset($request['allotted_quantity_rule']) && isset($request['rainbow_beans'])) {
+        if (isset($request['allotted_quantity_rule']) && isset($request['rainbow_beans'])) {
             $rule = $request['allotted_quantity_rule'];
             $rainbow_beans = $request['rainbow_beans'];
             $count = 0;
             if (count($rule) == count($rule, 1)) {
                 $count = array_sum($rule);
-                if ($count > $rainbow_beans){
+                if ($count > $rainbow_beans) {
                     throw new HttpException(500, '唯一行为-分配总数不能大于行为生成彩虹豆总数');
                 }
             } else {
-                foreach ($rule as $value){
+                foreach ($rule as $value) {
                     $count += $value['bean'];
                 }
-                if ($count > $rainbow_beans){
+                if ($count > $rainbow_beans) {
                     throw new HttpException(500, '多级行为-分配总数不能大于行为生成彩虹豆总数');
                 }
             }
@@ -203,14 +205,14 @@ class BehaviorRepository
         try {
             $res = $this->behavior->create($data);
             if ($res) {
-                $token =  JWTAuth::decode(JWTAuth::getToken());
+                $token = JWTAuth::decode(JWTAuth::getToken());
                 $uid = $token['user']->id;
                 $username = $token['user']->username;
                 $cerate_bahavior_data = [
                     'operator_id' => $uid,
                     'behavior_id' => $res['id'],
                     'username' => $username,
-                    'content' => '创建'.$request['name'].'行为',
+                    'content' => '创建' . $request['name'] . '行为',
                     'type' => 0,
                     'created_at' => date('Y-m-d H:i:s'),
                     'updated_at' => date('Y-m-d H:i:s')
@@ -225,7 +227,7 @@ class BehaviorRepository
 
         } catch (QueryException $exception) {
             DB::rollBack();
-            Log::debug('注册行为:'.$exception->getMessage());
+            Log::debug('注册行为:' . $exception->getMessage());
             return Response::create([
                 'message' => '添加失败,请重试',
                 'error' => $exception->getMessage(),
@@ -237,7 +239,7 @@ class BehaviorRepository
     public function edit($request)
     {
         $behavior_id = $this->behavior->find($request['id']);
-        if ($behavior_id->is_open == 1){
+        if ($behavior_id->is_open == 1) {
             throw new HttpException(500, '无法编辑已经在记录的行为');
         }
         $update_bahavior = [
@@ -261,40 +263,40 @@ class BehaviorRepository
             'relative_series' => isset($request['relative_series']) ? $request['relative_series'] : 0,
             'absolute_progression' => isset($request['absolute_progression']) ? $request['absolute_progression'] : 0,
             'updated_at' => date('Y-m-d H:i:s')
-            ];
+        ];
         DB::beginTransaction();
-        try{
-            $res = $this->behavior->where('id',$request['id'])->update($update_bahavior);
-                if ($res) {
-                    $token =  JWTAuth::decode(JWTAuth::getToken());
-                    $uid = $token['user']->id;
-                    $username = $token['user']->username;
-                    $cerate_bahavior_data = [
-                        'operator_id' => $uid,
-                        'behavior_id' => $request['id'],
-                        'username' => $username,
-                        'content' => json_encode($update_bahavior),
-                        'type' => 1,
-                        'created_at' => date('Y-m-d H:i:s'),
-                        'updated_at' => date('Y-m-d H:i:s')
-                    ];
-                    $result = $this->behaviorOperationLog->insert($cerate_bahavior_data);
-                    if (!$result) {
-                        throw new HttpException(500, '操作日志记录失败');
-                    }
+        try {
+            $res = $this->behavior->where('id', $request['id'])->update($update_bahavior);
+            if ($res) {
+                $token = JWTAuth::decode(JWTAuth::getToken());
+                $uid = $token['user']->id;
+                $username = $token['user']->username;
+                $cerate_bahavior_data = [
+                    'operator_id' => $uid,
+                    'behavior_id' => $request['id'],
+                    'username' => $username,
+                    'content' => json_encode($update_bahavior),
+                    'type' => 1,
+                    'created_at' => date('Y-m-d H:i:s'),
+                    'updated_at' => date('Y-m-d H:i:s')
+                ];
+                $result = $this->behaviorOperationLog->insert($cerate_bahavior_data);
+                if (!$result) {
+                    throw new HttpException(500, '操作日志记录失败');
                 }
-                DB::commit();
-                return Response::create();
-
-            } catch (QueryException $exception) {
-                DB::rollBack();
-                Log::debug('编辑行为:'.$exception->getMessage());
-                return Response::create([
-                    'message' => '编辑失败,请重试',
-                    'error' => $exception->getMessage(),
-                    'status_code' => 500
-                ]);
             }
+            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 editStatus($request)
@@ -305,25 +307,25 @@ class BehaviorRepository
             'is_open' => $request['is_open'],
             'updated_at' => date('Y-m-d H:i:s')
         ];
-        if ($request['is_open'] == 0){
+        if ($request['is_open'] == 0) {
             $is_open = '关闭';
-        }else{
+        } else {
             $is_open = '开启';
         }
         $behavior_name = $behavior->name;
 
         DB::beginTransaction();
         try {
-            $res = $behavior->where('id',$request['id'])->update($behavior_array);
+            $res = $behavior->where('id', $request['id'])->update($behavior_array);
             if ($res) {
-                $token =  JWTAuth::decode(JWTAuth::getToken());
+                $token = JWTAuth::decode(JWTAuth::getToken());
                 $uid = $token['user']->id;
                 $username = $token['user']->username;
                 $cerate_bahavior_data = [
                     'operator_id' => $uid,
                     'behavior_id' => $request['id'],
                     'username' => $username,
-                    'content' => $is_open.'了'.$behavior_name.'行为',
+                    'content' => $is_open . '了' . $behavior_name . '行为',
                     'type' => 2,
                     'created_at' => date('Y-m-d H:i:s'),
                     'updated_at' => date('Y-m-d H:i:s')
@@ -364,39 +366,28 @@ class BehaviorRepository
         if(isset($request['name'])){
             $where[] = ['name', 'like', "%{$request['name']}%"];
         }
-        //触发次数由多到少-由少到多筛选
-        if (isset($request['trigger_times']) && $request['trigger_times'] == 0){
-            return $this->behavior->orderBy('trigger_times','desc')->paginate($perPage);
-        }elseif (isset($request['trigger_times']) && $request['trigger_times'] == 1){
-            return $this->behavior->orderBy('trigger_times','asc')->paginate($perPage);
-        }
-        //有效触发由多到少-由少到多筛选
-        if (isset($request['effective_trigger']) && $request['effective_trigger'] == 0){
-            return $this->behavior->orderBy('effective_trigger','desc')->paginate($perPage);
-        }elseif (isset($request['effective_trigger']) && $request['effective_trigger'] == 1){
-            return $this->behavior->orderBy('effective_trigger','asc')->paginate($perPage);
-        }
-        //绝对级数由多到少-由少到多筛选
-        if (isset($request['absolute_progression']) && $request['absolute_progression'] == 0){
-            return $this->behavior->orderBy('absolute_progression','desc')->paginate($perPage);
-        }elseif (isset($request['absolute_progression']) && $request['absolute_progression'] == 1){
-            return $this->behavior->orderBy('absolute_progression','asc')->paginate($perPage);
-        }
-        //耗费体力值由多到少-由少到多筛选
-        if (isset($request['physical_strength']) && $request['physical_strength'] == 0){
-            return $this->behavior->orderBy('physical_strength','desc')->paginate($perPage);
-        }elseif (isset($request['physical_strength']) && $request['physical_strength'] == 1){
-            return $this->behavior->orderBy('physical_strength','asc')->paginate($perPage);
-        }
-        //发放彩虹豆由多到少-由少到多筛选
-        if (isset($request['grant_rainbow_beans']) && $request['grant_rainbow_beans'] == 0){
-            return $this->behavior->orderBy('grant_rainbow_beans','desc')->paginate($perPage);
-        }elseif (isset($request['grant_rainbow_beans']) && $request['grant_rainbow_beans'] == 1){
-            return $this->behavior->orderBy('grant_rainbow_beans','asc')->paginate($perPage);
-        }
 
-        return $this->behavior->where($where)->paginate($perPage);
+        if(isset($request['trigger_times'])){//触发次数由多到少-由少到多筛选
+            $filed = 'trigger_times';
+            $sort = $request['trigger_times']   == 0 ? 'desc' : 'asc';
+        }elseif(isset($request['effective_trigger'])){//有效触发由多到少-由少到多筛选
+            $filed = 'effective_trigger';
+            $sort=$request['effective_trigger']  == 0 ? 'desc' : 'asc';
+        }elseif (isset($request['absolute_progression'])){////绝对级数由多到少-由少到多筛选
+            $filed = 'absolute_progression';
+            $sort=$request['absolute_progression']  == 0 ? 'desc' : 'asc';
+        }elseif (isset($request['physical_strength'])){//耗费体力值由多到少-由少到多筛选
+            $filed = 'physical_strength';
+            $sort=$request['physical_strength']  == 0 ? 'desc' : 'asc';
+        }elseif (isset($request['grant_rainbow_beans'])) {//发放彩虹豆由多到少-由少到多筛选
+            $filed = 'grant_rainbow_beans';
+            $sort = $request['grant_rainbow_beans'] == 0 ? 'desc' : 'asc';
+        }else{
+            $sort = 'desc';
+            $filed = 'id';
+        }
 
+        return $this->behavior->where($where)->orderBy($filed,$sort)->paginate($perPage);
     }
 
 }

+ 219 - 152
app/Repositories/Post/PostRepository.php

@@ -6,6 +6,7 @@
  * Date: 2019/6/5
  * Time: 16:03
  */
+
 namespace App\Repositories\Post;
 
 use App\Models\CategoryTopic;
@@ -14,6 +15,7 @@ use App\Models\PostComment;
 use App\Models\PostData;
 use App\Models\PostImgs;
 use App\Models\PostLog;
+use App\Models\PostStatistics;
 use App\Models\Topic;
 use App\Service\RabbitMqUtil;
 use App\Traits\PostTrait;
@@ -41,6 +43,7 @@ class PostRepository
                                 PostLog $postLog,
                                 RabbitMqUtil $rabbitMqUtil,
                                 CategoryTopic $categoryTopic,
+                                PostStatistics $postStatistics,
                                 Topic $topic)
     {
         $this->post = $post;
@@ -51,6 +54,7 @@ class PostRepository
         $this->rabbitMqUtil = $rabbitMqUtil;
         $this->categoryTopic = $categoryTopic;
         $this->topic = $topic;
+        $this->postStatistics = $postStatistics;
     }
 
     /**
@@ -70,10 +74,10 @@ class PostRepository
         //验证话题
         $topicIdsArray = $this->topic->whereIn('id', explode(',', $request['topic_ids']))->pluck('id')->toArray();
         $topicCount = count($topicIdsArray);
-        if($topicCount == 0 || $topicCount > 5){
+        if ($topicCount == 0 || $topicCount > 5) {
             return Response::create([
-                'message'  => '所选话题必须1-5个',
-                'status_code'   => 500
+                'message' => '所选话题必须1-5个',
+                'status_code' => 500
             ]);
         }
         $topicIds = implode(',', $topicIdsArray);
@@ -82,8 +86,8 @@ class PostRepository
         $html = strip_tags($request['content']);
         if(mb_strlen($html,'UTF8') > 1000){
             return Response::create([
-                'message'  => '所传内容不能超过1000字',
-                'status_code'   => 500
+                'message' => '所传内容不能超过1000字',
+                'status_code' => 500
             ]);
         }
 
@@ -94,11 +98,11 @@ class PostRepository
             'avatar' => 'https://wx.qlogo.cn/mmopen/vi_32/DYAIOgq83ep3asJn8emiat1MnPdviaPNroWY3f65y5ezkTAk2qtibv7ea9Ht9R2ahxr9bicY1DIj5vN5FibpDOwXegg/132',
             'type' => $request['type'],
             'img' => $request['img'],
-            'video' => $request['video']??'',
+            'video' => $request['video'] ?? '',
             'topic_ids' => $topicIds,
-            'title' => $request['title']??'',
+            'title' => $request['title'] ?? '',
             'content' => $request['content'],
-            'location' => $request['location']??'',
+            'location' => $request['location'] ?? '',
             'is_suggest' => $request['is_suggest'],
             'is_hide' => 0
         ];
@@ -107,7 +111,7 @@ class PostRepository
 
 
         DB::beginTransaction();
-        try{
+        try {
             $post = $this->post->create($data);
 
             $this->postData->create([
@@ -128,9 +132,9 @@ class PostRepository
                 'weight' => 0
             ]);
 
-            if(!empty($request['imgs']) && $request['type'] == 'image'){
+            if (!empty($request['imgs']) && $request['type'] == 'image') {
                 $imgData = [];
-                foreach($request['imgs'] as $img){
+                foreach ($request['imgs'] as $img) {
                     $imgData[] = [
                         'post_id' => $post->id,
                         'img' => $img,
@@ -143,18 +147,18 @@ class PostRepository
 
             DB::commit();
             Redis::zadd('post_trigger_type', 0, $post->id);
-            foreach($topicIdsArray as $id){
-                Redis::zincrby('topic.user_uid'.$request['uid'], 1, $id);
+            foreach ($topicIdsArray as $id) {
+                Redis::zincrby('topic.user_uid' . $request['uid'], 1, $id);
             }
             return Response::create();
 
-        }catch (QueryException $exception){
+        } catch (QueryException $exception) {
             DB::rollBack();
-            Log::debug('发布内容:'.$exception->getMessage());
+            Log::debug('发布内容:' . $exception->getMessage());
             return Response::create([
-                'message'  => '发布失败,请重试',
+                'message' => '发布失败,请重试',
                 'error' => $exception->getMessage(),
-                'status_code'   => 500
+                'status_code' => 500
             ]);
         }
     }
@@ -164,11 +168,11 @@ class PostRepository
      */
     public function addData($request)
     {
-        $token =  JWTAuth::decode(JWTAuth::getToken());
-        if(!$token || $token['type'] != 1){
+        $token = JWTAuth::decode(JWTAuth::getToken());
+        if (!$token || $token['type'] != 1) {
             return Response::create([
-                'message'  => '获取登陆信息失败',
-                'status_code'   => 500
+                'message' => '获取登陆信息失败',
+                'status_code' => 500
             ]);
         }
         $uid = $token['user']->id;
@@ -176,17 +180,17 @@ class PostRepository
         //验证小号数量
 
         $postData = $this->postData->where('post_id', $request['post_id'])->first();
-        if(!$postData){
+        if (!$postData) {
             return Response::create([
-                'message'  => '获取内容失败',
-                'status_code'   => 500
+                'message' => '获取内容失败',
+                'status_code' => 500
             ]);
         }
 
-        if($request['add_pv'] == 0 && $request['add_praise_count'] == 0 && $request['add_collect_count'] == 0 && $request['add_share_count'] == 0){
+        if ($request['add_pv'] == 0 && $request['add_praise_count'] == 0 && $request['add_collect_count'] == 0 && $request['add_share_count'] == 0) {
             return Response::create([
-                'message'  => '增加数据不能同时为0',
-                'status_code'   => 500
+                'message' => '增加数据不能同时为0',
+                'status_code' => 500
             ]);
         }
         $content = [
@@ -195,24 +199,24 @@ class PostRepository
             'add_collect_count' => 0,
             'add_share_count' => 0,
         ];
-        if($request['add_pv']){
+        if ($request['add_pv']) {
             $postData->pv += $request['add_pv'];
             $content['add_pv'] = $request['add_pv'];
         }
-        if($request['add_praise_count']){
+        if ($request['add_praise_count']) {
             $postData->praise_count += $request['add_praise_count'];
             $content['add_praise_count'] = $request['add_praise_count'];
         }
-        if($request['add_collect_count']){
+        if ($request['add_collect_count']) {
             $postData->collect_count += $request['add_collect_count'];
             $content['add_collect_count'] = $request['add_collect_count'];
         }
-        if($request['add_share_count']){
+        if ($request['add_share_count']) {
             $postData->share_count += $request['add_share_count'];
             $content['add_share_count'] = $request['add_share_count'];
         }
         DB::beginTransaction();
-        try{
+        try {
             $postData->save();
             $this->postLog->create([
                 'post_id' => $request['post_id'],
@@ -225,13 +229,13 @@ class PostRepository
             DB::commit();
             return Response::create();
 
-        }catch (QueryException $exception){
+        } catch (QueryException $exception) {
             DB::rollBack();
-            Log::debug('内容增加数据:'.$request['post_id'].$exception->getMessage());
+            Log::debug('内容增加数据:' . $request['post_id'] . $exception->getMessage());
             return Response::create([
-                'message'  => '增加数据失败,请重试',
+                'message' => '增加数据失败,请重试',
                 'error' => $exception->getMessage(),
-                'status_code'   => 500
+                'status_code' => 500
             ]);
         }
     }
@@ -243,19 +247,19 @@ class PostRepository
     {
         //验证小号
         $userInfo = $this->getUserInfo($request['uid']);
-        Log::debug('评论&回复小号'.json_encode($userInfo));
-        if(!$userInfo || $userInfo['type'] != 1){
+        Log::debug('评论&回复小号' . json_encode($userInfo));
+        if (!$userInfo || $userInfo['type'] != 1) {
             return Response::create([
-                'message'  => '所选小号信息有误',
-                'status_code'   => 500
+                'message' => '所选小号信息有误',
+                'status_code' => 500
             ]);
         }
 
         $post = $this->post->find($request['post_id']);
-        if(!$post){
+        if (!$post) {
             return Response::create([
-                'message'  => '获取内容失败',
-                'status_code'   => 500
+                'message' => '获取内容失败',
+                'status_code' => 500
             ]);
         }
         $data = [
@@ -269,18 +273,18 @@ class PostRepository
             'content' => $request['content'],
             'is_delete' => 0,
         ];
-        if(isset($request['parent_id']) && $request['parent_id'] != 0){
+        if (isset($request['parent_id']) && $request['parent_id'] != 0) {
             $comment = $this->postComment->find($request['parent_id']);
-            if(!$comment){
+            if (!$comment) {
                 return Response::create([
-                    'message'  => '获取评论信息失败',
-                    'status_code'   => 500
+                    'message' => '获取评论信息失败',
+                    'status_code' => 500
                 ]);
             }
-            if($comment->parent_id){
+            if ($comment->parent_id) {
                 return Response::create([
-                    'message'  => '只能回复评论',
-                    'status_code'   => 500
+                    'message' => '只能回复评论',
+                    'status_code' => 500
                 ]);
             }
             $data['parent_id'] = $request['parent_id'];
@@ -297,7 +301,7 @@ class PostRepository
                     'content' => subtext($request['content'], 20),
                 ]
             ]);
-        }else{
+        } else {
             $this->rabbitMqUtil->push('add_message', [
                 'uid' => $post->uid,
                 'message_show_type' => 'post_comment',
@@ -311,7 +315,7 @@ class PostRepository
             ]);
         }
         DB::beginTransaction();
-        try{
+        try {
             $this->postComment->create($data);
             $post->data->comment_count += 1;
             $post->data->save();
@@ -319,13 +323,13 @@ class PostRepository
             DB::commit();
             return Response::create();
 
-        }catch (QueryException $exception){
+        } catch (QueryException $exception) {
             DB::rollBack();
-            Log::debug('评论内容:'.$request['post_id'].$exception->getMessage());
+            Log::debug('评论内容:' . $request['post_id'] . $exception->getMessage());
             return Response::create([
-                'message'  => '评论失败,请重试',
+                'message' => '评论失败,请重试',
                 'error' => $exception->getMessage(),
-                'status_code'   => 500
+                'status_code' => 500
             ]);
         }
     }
@@ -337,26 +341,26 @@ class PostRepository
     {
         $perPage = isset($request['per_page']) ? $request['per_page'] : 20;
         $where = [];
-        if(isset($request['content'])){
+        if (isset($request['content'])) {
             $where[] = ['content', 'like', "%{$request['content']}%"];
         }
-        if(isset($request['is_suggest'])){
+        if (isset($request['is_suggest'])) {
             $where[] = ['is_suggest', $request['is_suggest']];
         }
-        if(isset($request['type'])){
+        if (isset($request['type'])) {
             $where[] = ['type', $request['type']];
         }
 
-        if(isset($request['uid'])){
+        if (isset($request['uid'])) {
             $where[] = ['uid', $request['uid']];
         }
 
         $sort = 'post.id';
-        if(isset($request['sort']) && in_array($request['sort'], ['praise_count', 'share_count', 'pv', 'comment_count', 'create_bean'])){
+        if (isset($request['sort']) && in_array($request['sort'], ['praise_count', 'share_count', 'pv', 'comment_count', 'create_bean'])) {
             $sort = $request['sort'];
         }
         $post = $this->post;
-        if(isset($request['waste']) && $request['waste'] == 1){
+        if (isset($request['waste']) && $request['waste'] == 1) {
             $post = $post->onlyTrashed();
         }
 
@@ -364,21 +368,21 @@ class PostRepository
             ->join('post_data', 'post_data.post_id', '=', 'post.id')
             ->select('post.*')
             ->where($where)
-            ->where(function($query) use ($request){
-                if(isset($request['keyword'])){
+            ->where(function ($query) use ($request) {
+                if (isset($request['keyword'])) {
                     $query->where('uid', '=', $request['keyword'])
                         ->orWhere('username', 'like', "%{$request['keyword']}%")
                         ->orWhere('mobile', 'like', "%{$request['keyword']}%");
                 }
             })
-            ->where(function($query) use ($request){
-                if(isset($request['created_at'])){
+            ->where(function ($query) use ($request) {
+                if (isset($request['created_at'])) {
                     $time = explode('_', $request['created_at']);
                     $query->whereBetween('post.created_at', $time);
                 }
             })
-            ->where(function ($query) use ($request){
-                if(isset($request['category_ids']) || isset($request['topic_ids'])){
+            ->where(function ($query) use ($request) {
+                if (isset($request['category_ids']) || isset($request['topic_ids'])) {
                     $ids = [];
                     if (isset($request['category_ids'])) {
                         $categoryIds = explode('_', $request['category_ids']);
@@ -387,19 +391,19 @@ class PostRepository
                     if (isset($request['topic_ids'])) {
                         $ids = array_merge($ids, explode('_', $request['topic_ids']));
                     }
-                    foreach ($ids as $key=>$id) {
-                        if ($key==0) {
-                            $query = $query->whereRaw('FIND_IN_SET('.$id.',topic_ids)');
+                    foreach ($ids as $key => $id) {
+                        if ($key == 0) {
+                            $query = $query->whereRaw('FIND_IN_SET(' . $id . ',topic_ids)');
                         } else {
-                            $query = $query->orWhereRaw('FIND_IN_SET('.$id.',topic_ids)');
+                            $query = $query->orWhereRaw('FIND_IN_SET(' . $id . ',topic_ids)');
                         }
                     }
                 }
             })
-            ->orderBy($sort,'desc')
+            ->orderBy($sort, 'desc')
             ->paginate($perPage);
     }
-    
+
 
     /**
      * 内容详情
@@ -417,17 +421,17 @@ class PostRepository
         $perPage = isset($request['per_page']) ? $request['per_page'] : 20;
 
         $where = [];
-        if(isset($request['post_id'])){
+        if (isset($request['post_id'])) {
             $where[] = ['post_id', $request['post_id']];
         }
 
-        if(isset($request['uid'])){
+        if (isset($request['uid'])) {
             $where[] = ['uid', $request['uid']];
         }
 
         return $this->postComment
             ->where($where)
-            ->orderBy('id','desc')
+            ->orderBy('id', 'desc')
             ->paginate($perPage);
     }
 
@@ -437,33 +441,33 @@ class PostRepository
     public function suggest($request)
     {
         $post = $this->post->where('id', $request['id'])->first();
-        if(!$post){
+        if (!$post) {
             return Response::create([
-                'message'  => '获取内容信息失败',
-                'status_code'   => 500
+                'message' => '获取内容信息失败',
+                'status_code' => 500
             ]);
         }
 
-        if($post->is_suggest == 1){
+        if ($post->is_suggest == 1) {
             $post->is_suggest = 0;
-        }else{
+        } else {
             $post->is_suggest = 1;
         }
 
         DB::beginTransaction();
-        try{
+        try {
             $post->save();
 
             DB::commit();
             return Response::create();
 
-        }catch (QueryException $exception){
+        } catch (QueryException $exception) {
             DB::rollBack();
-            Log::debug('推荐内容:'.$request['id'].$exception->getMessage());
+            Log::debug('推荐内容:' . $request['id'] . $exception->getMessage());
             return Response::create([
-                'message'  => '操作失败,请重试',
+                'message' => '操作失败,请重试',
                 'error' => $exception->getMessage(),
-                'status_code'   => 500
+                'status_code' => 500
             ]);
         }
     }
@@ -474,27 +478,27 @@ class PostRepository
     public function delete($request)
     {
         $post = $this->post->where('id', $request['id'])->first();
-        if(!$post){
+        if (!$post) {
             return Response::create([
-                'message'  => '获取内容信息失败',
-                'status_code'   => 500
+                'message' => '获取内容信息失败',
+                'status_code' => 500
             ]);
         }
 
         DB::beginTransaction();
-        try{
+        try {
             $post->delete();
 
             DB::commit();
             return Response::create();
 
-        }catch (QueryException $exception){
+        } catch (QueryException $exception) {
             DB::rollBack();
-            Log::debug('删除内容:'.$request['id'].$exception->getMessage());
+            Log::debug('删除内容:' . $request['id'] . $exception->getMessage());
             return Response::create([
-                'message'  => '操作失败,请重试',
+                'message' => '操作失败,请重试',
                 'error' => $exception->getMessage(),
-                'status_code'   => 500
+                'status_code' => 500
             ]);
         }
     }
@@ -505,27 +509,27 @@ class PostRepository
     public function restore($request)
     {
         $post = $this->post->withTrashed()->where('id', $request['id'])->first();
-        if(!$post){
+        if (!$post) {
             return Response::create([
-                'message'  => '获取内容信息失败',
-                'status_code'   => 500
+                'message' => '获取内容信息失败',
+                'status_code' => 500
             ]);
         }
 
         DB::beginTransaction();
-        try{
+        try {
             $post->restore();
 
             DB::commit();
             return Response::create();
 
-        }catch (QueryException $exception){
+        } catch (QueryException $exception) {
             DB::rollBack();
-            Log::debug('复原内容:'.$request['id'].$exception->getMessage());
+            Log::debug('复原内容:' . $request['id'] . $exception->getMessage());
             return Response::create([
-                'message'  => '操作失败,请重试',
+                'message' => '操作失败,请重试',
                 'error' => $exception->getMessage(),
-                'status_code'   => 500
+                'status_code' => 500
             ]);
         }
     }
@@ -536,35 +540,35 @@ class PostRepository
     public function commentDelete($request)
     {
         $comment = $this->postComment->find($request['id']);
-        if(!$comment){
+        if (!$comment) {
             return Response::create([
-                'message'  => '获取评论信息失败',
-                'status_code'   => 500
+                'message' => '获取评论信息失败',
+                'status_code' => 500
             ]);
         }
 
-        if($comment->is_delete == 1){
+        if ($comment->is_delete == 1) {
             return Response::create([
-                'message'  => '该评论已经删除',
-                'status_code'   => 500
+                'message' => '该评论已经删除',
+                'status_code' => 500
             ]);
         }
 
         DB::beginTransaction();
-        try{
+        try {
             $comment->is_delete = 1;
             $comment->save();
 
             DB::commit();
             return Response::create();
 
-        }catch (QueryException $exception){
+        } catch (QueryException $exception) {
             DB::rollBack();
-            Log::debug('删除评论:'.$request['id'].$exception->getMessage());
+            Log::debug('删除评论:' . $request['id'] . $exception->getMessage());
             return Response::create([
-                'message'  => '操作失败,请重试',
+                'message' => '操作失败,请重试',
                 'error' => $exception->getMessage(),
-                'status_code'   => 500
+                'status_code' => 500
             ]);
         }
     }
@@ -575,33 +579,33 @@ class PostRepository
     public function hide($request)
     {
         $post = $this->post->where('id', $request['id'])->first();
-        if(!$post){
+        if (!$post) {
             return Response::create([
-                'message'  => '获取内容信息失败',
-                'status_code'   => 500
+                'message' => '获取内容信息失败',
+                'status_code' => 500
             ]);
         }
 
-        if($post->is_hide == 1){
+        if ($post->is_hide == 1) {
             $post->is_hide = 0;
-        }else{
+        } else {
             $post->is_hide = 1;
         }
 
         DB::beginTransaction();
-        try{
+        try {
             $post->save();
 
             DB::commit();
             return Response::create();
 
-        }catch (QueryException $exception){
+        } catch (QueryException $exception) {
             DB::rollBack();
-            Log::debug('隐藏内容:'.$request['id'].$exception->getMessage());
+            Log::debug('隐藏内容:' . $request['id'] . $exception->getMessage());
             return Response::create([
-                'message'  => '操作失败,请重试',
+                'message' => '操作失败,请重试',
                 'error' => $exception->getMessage(),
-                'status_code'   => 500
+                'status_code' => 500
             ]);
         }
     }
@@ -613,19 +617,19 @@ class PostRepository
     {
         $perPage = isset($request['per_page']) ? $request['per_page'] : 20;
         $where = [];
-        if(isset($request['log_type'])){
+        if (isset($request['log_type'])) {
             $where[] = ['log_type', $request['log_type']];
         }
 
         return $this->postLog
             ->where($where)
-            ->where(function($query) use ($request){
-                if(isset($request['created_at'])){
+            ->where(function ($query) use ($request) {
+                if (isset($request['created_at'])) {
                     $time = explode('_', $request['created_at']);
                     $query->whereBetween('created_at', $time);
                 }
             })
-            ->orderBy('id','desc')
+            ->orderBy('id', 'desc')
             ->paginate($perPage);
     }
 
@@ -641,11 +645,11 @@ class PostRepository
             $writer = Writer::createFromPath(public_path($filePath), 'w+');
 
             // 设置标题
-            if($type == 'post'){
+            if ($type == 'post') {
                 $title = [
                     '内容', date('Y年m月d日')
                 ];
-            }else{
+            } else {
                 $title = [
                     '回收站内容', date('Y年m月d日')
                 ];
@@ -655,7 +659,7 @@ class PostRepository
             $writer->insertone($title);
 
             // 内容
-            if($type == 'post') {
+            if ($type == 'post') {
                 $header = [
                     '内容ID', '发布时间', '用户昵称', '城市', '内容标签', '内容前20个字',
                     '真实浏览量', '总浏览量', '真实点赞数', '总赞数', '真实分享数', '总分享数',
@@ -673,43 +677,43 @@ class PostRepository
             $writer->insertone($header);
 
             $where = [];
-            if(isset($request['content'])){
+            if (isset($request['content'])) {
                 $where[] = ['content', 'like', "%{$request['content']}%"];
             }
-            if(isset($request['is_suggest'])){
+            if (isset($request['is_suggest'])) {
                 $where[] = ['is_suggest', $request['is_suggest']];
             }
-            if(isset($request['type'])){
+            if (isset($request['type'])) {
                 $where[] = ['type', $request['type']];
             }
 
             $sort = 'post.id';
-            if(isset($request['sort']) && in_array($request['sort'], ['praise_count', 'share_count', 'pv', 'comment_count', 'create_bean'])){
+            if (isset($request['sort']) && in_array($request['sort'], ['praise_count', 'share_count', 'pv', 'comment_count', 'create_bean'])) {
                 $sort = $request['sort'];
             }
             $post = $this->post;
-            if($type == 'post_waste'){
+            if ($type == 'post_waste') {
                 $post = $post->onlyTrashed();
             }
 
             $post->join('post_data', 'post_data.post_id', '=', 'post.id')
                 ->select('post.*')
                 ->where($where)
-                ->where(function($query) use ($request){
-                    if(isset($request['keyword'])){
+                ->where(function ($query) use ($request) {
+                    if (isset($request['keyword'])) {
                         $query->where('uid', '=', $request['keyword'])
                             ->orWhere('username', 'like', "%{$request['keyword']}%")
                             ->orWhere('mobile', 'like', "%{$request['keyword']}%");
                     }
                 })
-                ->where(function($query) use ($request){
-                    if(isset($request['created_at'])){
+                ->where(function ($query) use ($request) {
+                    if (isset($request['created_at'])) {
                         $time = explode('_', $request['created_at']);
                         $query->whereBetween('post.created_at', $time);
                     }
                 })
-                ->where(function ($query) use ($request){
-                    if(isset($request['category_ids']) || isset($request['topic_ids'])){
+                ->where(function ($query) use ($request) {
+                    if (isset($request['category_ids']) || isset($request['topic_ids'])) {
                         $ids = [];
                         if (isset($request['category_ids'])) {
                             $categoryIds = explode('_', $request['category_ids']);
@@ -718,21 +722,21 @@ class PostRepository
                         if (isset($request['topic_ids'])) {
                             $ids = array_merge($ids, explode('_', $request['topic_ids']));
                         }
-                        Log::debug('话题ids:'.json_encode($ids));
-                        foreach ($ids as $key=>$id) {
-                            if ($key==0) {
-                                $query = $query->whereRaw('FIND_IN_SET('.$id.',topic_ids)');
+                        Log::debug('话题ids:' . json_encode($ids));
+                        foreach ($ids as $key => $id) {
+                            if ($key == 0) {
+                                $query = $query->whereRaw('FIND_IN_SET(' . $id . ',topic_ids)');
                             } else {
-                                $query = $query->orWhereRaw('FIND_IN_SET('.$id.',topic_ids)');
+                                $query = $query->orWhereRaw('FIND_IN_SET(' . $id . ',topic_ids)');
                             }
                         }
                     }
                 })
-                ->orderBy($sort,'desc')
-                ->chunk(1, function ($posts) use ($writer, $type){
+                ->orderBy($sort, 'desc')
+                ->chunk(1, function ($posts) use ($writer, $type) {
                     $data = [];
                     foreach ($posts as $post) {
-                        if($type == 'post'){
+                        if ($type == 'post') {
                             $tmp = [
                                 $post->id,
                                 Carbon::parse($post->created_at)->toDateTimeString(),
@@ -750,7 +754,7 @@ class PostRepository
                                 $post->data->collect_count,
                                 $post->data->comment_count
                             ];
-                        }else{
+                        } else {
                             $tmp = [
                                 $post->id,
                                 Carbon::parse($post->created_at)->toDateTimeString(),
@@ -771,7 +775,7 @@ class PostRepository
                         $data[] = $tmp;
                     }
                     $writer->insertAll($data);
-            });
+                });
             Log::channel('download')->info('内容导出成功!');
 
         } catch (CannotInsertRecord $e) {
@@ -781,4 +785,67 @@ class PostRepository
 
     }
 
+    /**
+     * 统计社区内容
+     * @param $start
+     * @param $end
+     * @return array
+     */
+    public function statistics($start, $end)
+    {
+        $result = $this->postStatistics
+            ->where('created_at', '>=', $start)
+            ->where('created_at', '<=', $end)
+            ->get()->toArray();
+        $stimestamp = strtotime($start);
+        $etimestamp = strtotime($end);
+        $days = ($etimestamp - $stimestamp) / 86400;
+        $date = array();
+        for ($i = 0; $i < $days; $i++) {
+            $date[] = date('Y-m-d', $stimestamp + (86400 * $i));
+        }
+        $totalRead = 0;
+        $totalPost = 0;
+        $totalShare = 0;
+        $totalLike = 0;
+        $totalCollect = 0;
+        $totalComment = 0;
+        $info = [];
+        foreach ($date as $key => $value) {
+            $info[$value] = [
+                'read' => 0,
+                'post' => 0,
+                'share' => 0,
+                'like' => 0,
+                'collect' => 0,
+                'comment' => 0,
+            ];
+            foreach ($result as $row) {
+                if ($value == date('Y-m-d', strtotime($row['created_at']))) {
+                    $info[$value]['read'] = $row['read_count'];
+                    $info[$value]['post'] = $row['post_count'];
+                    $info[$value]['share'] = $row['share_count'];
+                    $info[$value]['like'] = $row['like_count'];
+                    $info[$value]['collect'] = $row['collect_count'];
+                    $info[$value]['comment'] = $row['comment_count'];
+                    $totalRead += $row['read_count'];
+                    $totalPost += $row['post_count'];
+                    $totalShare += $row['share_count'];
+                    $totalLike += $row['like_count'];
+                    $totalCollect += $row['collect_count'];
+                    $totalComment += $row['comment_count'];
+                }
+            }
+        }
+
+        $info['data']['total_read'] = $totalRead;
+        $info['data']['total_post'] = $totalPost;
+        $info['data']['total_share'] = $totalShare;
+        $info['data']['total_like'] = $totalLike;
+        $info['data']['total_collect'] = $totalCollect;
+        $info['data']['total_comment'] = $totalComment;
+        return $info;
+    }
+
+
 }

+ 37 - 0
database/migrations/2019_06_20_011008_create_community_statistics_table.php

@@ -0,0 +1,37 @@
+<?php
+
+use Illuminate\Support\Facades\Schema;
+use Illuminate\Database\Schema\Blueprint;
+use Illuminate\Database\Migrations\Migration;
+
+class CreateCommunityStatisticsTable extends Migration
+{
+    /**
+     * Run the migrations.
+     *
+     * @return void
+     */
+    public function up()
+    {
+        Schema::create('community_statistics', function (Blueprint $table) {
+            $table->bigIncrements('id');
+            $table->integer('post_count')->nullable()->default(0)->comment('内容数');
+            $table->integer('read_count')->nullable()->default(0)->comment('阅读数');
+            $table->integer('share_count')->nullable()->default(0)->comment('分享数');
+            $table->integer('like_count')->nullable()->default(0)->comment('点赞数');
+            $table->integer('collect_count')->nullable()->default(0)->comment('收藏数');
+            $table->integer('comment_count')->nullable()->default(0)->comment('评论数');
+            $table->timestamps();
+        });
+    }
+
+    /**
+     * Reverse the migrations.
+     *
+     * @return void
+     */
+    public function down()
+    {
+        Schema::dropIfExists('community_statistics');
+    }
+}

+ 1 - 0
routes/api.php

@@ -27,6 +27,7 @@ $api->version('v1', [
         $api->post('download', 'DownloadController@create');
 
         $api->group(['namespace' => 'Post'], function ($api) {
+            $api->get('statistics', 'PostController@statistics');
             //发布内容
             $api->post('post', 'PostController@create');
             //内容列表