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

优化后的获取网站所有文章接口

15313670163 пре 1 недеља
родитељ
комит
cd22cdbdd7
1 измењених фајлова са 242 додато и 158 уклоњено
  1. 242 158
      app/JsonRpc/NewsService.php

+ 242 - 158
app/JsonRpc/NewsService.php

@@ -975,179 +975,257 @@ class NewsService implements NewsServiceInterface
         }
         return Result::success($category);
     }
-     /**
-     * 模块新闻加强plus版 
-     * @param array $data
-     * @return array
-    */
+    /**
+     * 优化后的获取网站所有文章接口
+     * 
+     * @param array $data 请求数据
+     * @return array 处理结果
+     */
     public function getWebsiteAllArticle(array $data): array
     {
-            // 修正传入的字符串,将单引号替换为双引号
-            $input['id'] = $data['id'];
-            $input['website_id'] = $data['website_id'];
+        try {
+            // 解析输入数据
+            $input = [
+                'id' => $data['id'] ?? '',
+                'website_id' => $data['website_id'] ?? 0
+            ];
+            
+            // 验证必要参数
+            if (empty($input['website_id'])) {
+                return Result::error("缺少网站ID参数", 0);
+            }
+            
             // 将 JSON 字符串转换为 PHP 数组
-            $data = json_decode($input['id'], true);
-            // 使用 array_map 处理每个元素
-            $result = array_map(function ($item) use ($input) {
-                // 检查parent元素是否存在且不是undefined
-                if (isset($item['parent']) && $item['parent'] != 'undefined' && $item['parent']!= "" ) {
-                    $count = explode(',', $item['parent']);
-                    if(count($count)!=3){
-                        return Result::error("父级栏目:缺少必需参数错误",0);
-                    }
-                    list($parentCatId, $parentImgNum, $parentTextNum) = explode(',', $item['parent']);
-                    $website = [
-                        'website_id' => $input['website_id'],
-                    ];
-                    // 查询栏目名称
-                    $categroy = WebsiteCategory::where('category_id', $parentCatId)->where($website)->first(['alias', 'category_id','aLIas_pinyin','type']);
-                    // 查询图片新闻
-                    if(isset($parentImgNum) && $parentImgNum!=0 && !empty($categroy)){
-                        $imgArticles = Article::where('article.status', 1)
-                        ->where(function($query) use ($parentCatId) {
-                            $query->whereRaw("JSON_CONTAINS(cat_arr_id, '\"$parentCatId\"')")
-                                    ->orWhereRaw("JSON_CONTAINS(cat_arr_id, '$parentCatId')");
-                        })
-                        ->where(function ($query) use ($website) {
-                            $query->where(function ($subQuery) use ($website) {
-                                $subQuery->whereRaw("JSON_CONTAINS(ignore_ids, '".intval($website['website_id'])."') = 0")
-                                    ->orWhereNull("ignore_ids");
-                            });
-                        })
-                        ->where('imgurl', '!=', '')
-                        ->leftJoin('website_category', function($join) use ($website) {
-                            $join->on('article.catid', '=', 'website_category.category_id')
-                                ->where('website_category.website_id', '=', $website['website_id']);
-                        })
-                        ->select(
-                            'article.id','article.title','article.imgurl','article.author','article.updated_at',
-                            'article.introduce','article.islink','article.linkurl','article.copyfrom','article.cat_arr_id',
-                            'article.catid','website_category.alias as category_name',
-                        )
-                        ->orderBy('updated_at', 'desc')
-                        ->limit($parentImgNum)
-                        ->get();    
-                        //调取封装路由的方法,处理新闻路由   
-                        if(!empty($imgArticles)){
-                            $imgArticles = $this->processArticles($imgArticles , $website);
-                        }
+            $items = json_decode($input['id'], true);
+            
+            if (json_last_error() !== JSON_ERROR_NONE || !is_array($items)) {
+                return Result::error("无效的JSON格式", 0);
+            }
+            
+            // 提取所有需要查询的分类ID
+            $parentCatIds = [];
+            $childCatIds = [];
+            
+            foreach ($items as $item) {
+                if (isset($item['parent']) && $item['parent'] && $item['parent'] !== 'undefined') {
+                    $parts = explode(',', $item['parent']);
+                    if (count($parts) === 3) {
+                        $parentCatIds[] = $parts[0];
                     }
-                    // 查询文字新闻
-                    if(isset($parentTextNum) && $parentTextNum!=0 && !empty($categroy)){  
-                        $textArticles = [];
-                        $textArticles = Article::where('article.status', 1)
-                            ->where(function($query) use ($parentCatId) {
-                                $query->whereRaw("JSON_CONTAINS(cat_arr_id, '\"$parentCatId\"')")
-                                        ->orWhereRaw("JSON_CONTAINS(cat_arr_id, '$parentCatId')");
-                            })
-                            ->where(function ($query) use ($website) {
-                                $query->where(function ($subQuery) use ($website) {
-                                    $subQuery->whereRaw("JSON_CONTAINS(ignore_ids, '".intval($website['website_id'])."') = 0")
-                                        ->orWhereNull("ignore_ids");
-                                });
-                            })
-                            ->leftJoin('website_category', function($join) use ($website) {
-                                $join->on('article.catid', '=', 'website_category.category_id')
-                                    ->where('website_category.website_id', '=', $website['website_id']);
-                            })
-                            ->select(
-                                'article.id','article.title','article.author','article.updated_at','article.cat_arr_id',
-                                'article.introduce','article.islink','article.linkurl','article.copyfrom',
-                                'article.catid','website_category.alias as category_name',
-                            )
-                            ->orderBy('updated_at', 'desc')
-                            ->limit($parentTextNum)
-                            ->get();
-                        if(!empty($textArticles)){
-                            $textArticles = $this->processArticles($textArticles , $website);
-                        }
+                }
+                
+                if (isset($item['child']) && $item['child'] && $item['child'] !== 'undefined') {
+                    $parts = explode(',', $item['child']);
+                    if (count($parts) === 3) {
+                        $childCatIds[] = $parts[0];
                     }
                 }
+            }
+            
+            // 去重分类ID
+            $parentCatIds = array_unique($parentCatIds);
+            $childCatIds = array_unique($childCatIds);
+            
+            // 批量查询分类信息
+            $websiteCondition = ['website_id' => $input['website_id']];
+            $categories = $this->getCategoriesByIds(array_merge($parentCatIds, $childCatIds), $websiteCondition);
+            
+            // 处理每个项目
+            $result = [];
+            foreach ($items as $item) {
                 $resultItem = [
-                    'alias' =>  $categroy ? $categroy->alias : null,
-                    'category_id' =>  $categroy ? $categroy->category_id : null,
-                    'pinyin' =>  $categroy ? $categroy->aLIas_pinyin : null,
-                    'imgnum' => $imgArticles ?? [],
-                    'textnum' => $textArticles ?? [],
+                    'alias' => null,
+                    'category_id' => null,
+                    'pinyin' => null,
+                    'imgnum' => [],
+                    'textnum' => [],
+                    'child' => []
                 ];
-                // 子级栏目
-                if(isset($item['child']) && $item['child'] != 'undefined' && $item['child'] != ""){
-                    $count = explode(',', $item['child']);
-                    if(count($count)!=3){
-                        return Result::error("子级栏目:缺少必需参数错误",0);
+                
+                // 处理父级栏目
+                if (isset($item['parent']) && $item['parent'] && $item['parent'] !== 'undefined') {
+                    $parts = explode(',', $item['parent']);
+                    
+                    if (count($parts) !== 3) {
+                        return Result::error("父级栏目:缺少必需参数错误", 0);
                     }
-                    list($childCatId, $childImgNum, $childTextNum) = explode(',', $item['child']);
-                    $childCategory = WebsiteCategory::where($website)
-                        ->where("category_id", $childCatId)
-                        ->whereRaw("JSON_CONTAINS(category_arr_id, '".intval($childCatId)."') = 1")
-                        ->first(['alias', 'category_id','aLIas_pinyin','pid','category_arr_id as cat_arr_id']);
-                    if (!empty($childCategory)) {
-                        $childCategory = $this->processArticles($childCategory, $website);
+                    
+                    list($parentCatId, $parentImgNum, $parentTextNum) = $parts;
+                    
+                    // 从已查询的分类中获取信息
+                    $category = $categories[$parentCatId] ?? null;
+                    
+                    if ($category) {
+                        $resultItem['alias'] = $category->alias;
+                        $resultItem['category_id'] = $category->category_id;
+                        $resultItem['pinyin'] = $category->alias_pinyin;
+                        
+                        // 查询图片新闻
+                        if ($parentImgNum > 0) {
+                            $resultItem['imgnum'] = $this->getArticles(
+                                $parentCatId, 
+                                $input['website_id'], 
+                                (int) $parentImgNum, 
+                                true
+                            );
+                        }
+                        
+                        // 查询文字新闻
+                        if ($parentTextNum > 0) {
+                            $resultItem['textnum'] = $this->getArticles(
+                                $parentCatId, 
+                                $input['website_id'], 
+                                (int) $parentTextNum, 
+                                false
+                            );
+                        }
+                    }
+                }
+                // 处理子级栏目
+                if (isset($item['child']) && $item['child'] && $item['child'] !== 'undefined') {
+                    $parts = explode(',', $item['child']);
+                    
+                    if (count($parts) !== 3) {
+                        return Result::error("子级栏目:缺少必需参数错误", 0);
+                    }
+                    
+                    list($childCatId, $childImgNum, $childTextNum) = $parts;
+                    
+                    // 从已查询的分类中获取信息
+                    $childCategory = $categories[$childCatId] ?? null;
+                    
+                    if ($childCategory) {
+                        $childData = [
+                            'alias' => $childCategory->alias,
+                            'category_id' => $childCategory->category_id,
+                            'pinyin' => $childCategory->alias_pinyin,
+                            'all_childcat' => [],
+                            'imgnum' => [],
+                            'textnum' => []
+                        ];
                         // 查询此层级的所有子栏目
-                        $all_childcat = WebsiteCategory::where($website)
-                        ->where("pid", $childCategory['pid'])
-                        // ->whereRaw("JSON_CONTAINS(category_arr_id, '".intval($childCatId)."') = 1")
-                        ->get(['alias', 'category_id','aLIas_pinyin','pid','category_arr_id as cat_arr_id']);
-                        $all_childcat = $this->processArticles($all_childcat, $website);
+                        $childData['all_childcat'] = $this->getChildCategories(
+                            $childCategory->pid,
+                            $input['website_id']
+                        );
+                        
                         // 查询子栏目图片新闻
-                        if( isset($childImgNum) && $childImgNum!=0 ){
-                            $childImgArticles = Article::where(function($query) use ($childCatId) {
-                                $query->whereRaw("JSON_CONTAINS(cat_arr_id, '\"$childCatId\"')")
-                                        ->orWhereRaw("JSON_CONTAINS(cat_arr_id, '$childCatId')");
-                                })
-                                ->where('status', 1)
-                                ->where(function ($query) use ($website) {
-                                    $query->where(function ($subQuery) use ($website) {
-                                        $subQuery->whereRaw("JSON_CONTAINS(ignore_ids, '".intval($website['website_id'])."') = 0");
-                                    })->orWhereNull("ignore_ids");
-                                })
-                                ->select('article.id','article.title','article.imgurl','article.author',
-                                    'article.updated_at','article.introduce','article.islink','article.linkurl',
-                                    'article.catid','article.cat_arr_id','article.copyfrom',)
-                                ->where('imgurl', '!=', '')
-                                ->orderBy('updated_at', 'desc')
-                                ->limit($childImgNum)
-                                ->get();
-                            $childImgArticles = $this->processArticles($childImgArticles, $website);
+                        if ($childImgNum > 0) {
+                            $childData['imgnum'] = $this->getArticles(
+                                $childCatId, 
+                                $input['website_id'], 
+                                (int) $childImgNum, 
+                                true
+                            );
                         }
                         // 查询子栏目文字新闻
-                        if( isset($childTextNum) && $childTextNum!=0 ){
-                            $childTextArticles = Article::where(function($query) use ($childCatId) {
-                                $query->whereRaw("JSON_CONTAINS(cat_arr_id, '\"$childCatId\"')")
-                                        ->orWhereRaw("JSON_CONTAINS(cat_arr_id, '$childCatId')");
-                                })
-                                ->where('status', 1)
-                                ->where(function ($query) use ($website) {
-                                    $query->where(function ($subQuery) use ($website) {
-                                        $subQuery->whereRaw("JSON_CONTAINS(ignore_ids, '".intval($website['website_id'])."') = 0");
-                                    })->orWhereNull("ignore_ids");
-                                })
-                                ->select('article.id','article.title','article.author','article.updated_at','article.introduce',
-                                    'article.islink','article.linkurl','article.catid','article.cat_arr_id','article.copyfrom',)
-                                ->orderBy('updated_at', 'desc')
-                                ->limit($childTextNum)
-                                ->get();
-                            $childTextArticles = $this->processArticles($childTextArticles, $website); 
+                        if ($childTextNum > 0) {
+                            $childData['textnum'] = $this->getArticles(
+                                $childCatId, 
+                                $input['website_id'], 
+                                (int) $childTextNum, 
+                                false
+                            );
                         }
+                        
+                        $resultItem['child'] = $childData;
                     }
-                    $resultItem['child'] = [
-                        'alias' => $childCategory ? $childCategory->alias : null,
-                        'category_id' => $childCategory ? $childCategory->category_id : null,
-                        'pinyin' => $childCategory ? $childCategory->pinyin : null,
-                        'all_childcat' => $all_childcat ?? [],
-                        'imgnum' => $childImgArticles ?? [],
-                        'textnum' => $childTextArticles ?? [],
-                    ];  
-                }else{
-                    $resultItem['child'] = [];
                 }
-            return $resultItem;
-        }, $data);
-        return Result::success($result);
-                // return Result::success($data);
+                
+                $result[] = $resultItem;
+            }
+            
+            return Result::success($result);
+        } catch (\Exception $e) {
+            return Result::error("处理请求时出错: " . $e->getMessage(), 0);
+        }
     }
-
-
+    
+    /**
+     * 批量获取分类信息
+     * 
+     * @Cacheable(prefix="categories", value="#{ids}_{website['website_id']}", ttl=3600)
+     */
+    protected function getCategoriesByIds(array $ids, array $website): array
+    {
+        if (empty($ids)) {
+            return [];
+        }
+        
+        $categories = WebsiteCategory::whereIn('category_id', $ids)
+            ->where($website)
+            ->get(['alias', 'category_id', 'alias_pinyin', 'type', 'pid', 'category_arr_id']);
+            
+        $result = [];
+        foreach ($categories as $category) {
+            $result[$category->category_id] = $category;
+        }
+        
+        return $result;
+    }
+    
+    /**
+     * 获取文章列表
+     * 
+     * @Cacheable(prefix="articles", value="#{catId}_{websiteId}_{limit}_{isImage}", ttl=300)
+     */
+    protected function getArticles(int $catId, int $websiteId, int $limit, bool $isImage = false): array
+    {
+        $query = Article::where('article.status', 1)
+            ->where(function($query) use ($catId) {
+                $query->whereRaw("JSON_CONTAINS(cat_arr_id, '\"$catId\"')")
+                    ->orWhereRaw("JSON_CONTAINS(cat_arr_id, '$catId')");
+            })
+            ->where(function ($query) use ($websiteId) {
+                $query->where(function ($subQuery) use ($websiteId) {
+                    $subQuery->whereRaw("JSON_CONTAINS(ignore_ids, '$websiteId') = 0")
+                        ->orWhereNull("ignore_ids");
+                });
+            })
+            ->leftJoin('website_category', function($join) use ($websiteId) {
+                $join->on('article.catid', '=', 'website_category.category_id')
+                    ->where('website_category.website_id', '=', $websiteId);
+            })
+            ->select(
+                'article.id', 'article.title', 'article.imgurl', 'article.author', 'article.updated_at',
+                'article.introduce', 'article.islink', 'article.linkurl', 'article.copyfrom', 'article.cat_arr_id',
+                'article.catid', 'website_category.alias as category_name',
+            )
+            ->orderBy('updated_at', 'desc')
+            ->limit($limit);
+            
+        if ($isImage) {
+            $query->where('imgurl', '!=', '');
+        }
+        
+        $articles = $query->get();
+        
+        // 处理文章路由
+        if (!empty($articles)) {
+            $articles = $this->processArticles($articles, ['website_id' => $websiteId]);
+        }
+        
+        return $articles->toArray();
+    }
+    
+    /**
+     * 获取子分类
+     * 
+     * @Cacheable(prefix="child_categories", value="#{pid}_{websiteId}", ttl=3600)
+     */
+    protected function getChildCategories(int $pid, int $websiteId): array
+    {
+        $categories = WebsiteCategory::where('website_id', $websiteId)
+            ->where("pid", $pid)
+            ->get(['alias', 'category_id', 'alias_pinyin', 'pid', 'category_arr_id']);
+            
+        // 处理分类路由
+        if (!empty($categories)) {
+            $categories = $this->processArticles($categories, ['website_id' => $websiteId]);
+        }
+        
+        return $categories->toArray();
+    }     
     /**
      * 乡村网-获取特殊新闻模块
      * @param array $data
@@ -1436,7 +1514,7 @@ class NewsService implements NewsServiceInterface
         $category = WebsiteCategory::where('website_id', $website) 
             ->whereRaw("JSON_CONTAINS(category_arr_id, '". intval($data['id']). "') = 1") 
             ->orWhereRaw("JSON_CONTAINS(category_arr_id, '\"". intval($data['id']). "\"') = 1") 
-            ->select('category_id', 'alias','aLIas_pinyin','pid','category_arr_id') 
+            ->select('category_id', 'alias','aLIas_pinyin','pid','category_arr_id' ,'sort') 
             ->orderBy('sort') 
             ->get(); 
         $cat =  $category->map(function ($item) use ($website) { 
@@ -1581,7 +1659,13 @@ class NewsService implements NewsServiceInterface
         // 检查 $articles 是否为数组或可迭代对象
         if (is_array($articles) || is_iterable($articles) &&!empty($articles)) {
             return $articles->map(function ($article) use ($data) {
-                $catid = $article->cat_arr_id?? '';
+                if(isset($article->cat_arr_id) &&!empty($article->cat_arr_id)){
+                    $catid = $article->cat_arr_id?? '';
+                }
+                if(isset($article->category_arr_id) &&!empty($article->category_arr_id)){
+                    $catid = $article->category_arr_id?? '';
+                }
+                // $catid = $article->cat_arr_id ||  $article->category_arr_id ?? '';
                 $level = json_decode($catid, true);
                 if (!is_array($level)) {
                     return $article;