tp/app/index/controller/Article/NewsCenterController.php
2026-03-20 09:12:57 +08:00

146 lines
3.7 KiB
PHP
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

<?php
declare(strict_types=1);
namespace app\index\controller\Article;
use app\index\BaseController;
use Symfony\Component\VarDumper\VarDumper;
use think\exception\ValidateException;
use think\facade\Request;
use think\facade\Session;
use think\response\Json;
use think\db\exception\DbException;
use app\model\Cms\Articles;
use app\model\Cms\ArticlesCategory;
class NewsCenterController extends BaseController
{
/**
* 根据域名获取新闻数据
* @return Json
*/
public function getCenterNews(): Json
{
$baseUrl = $this->request->get('baseUrl', '');
if (!empty($baseUrl)) {
$this->tenantId = BaseController::getTenantIdByDomain($baseUrl);
}
$tid = $this->getTenantId();
if (empty($tid)) {
return json([
'code' => 400,
'msg' => '无法识别租户信息',
'list' => [],
]);
}
// 查询该租户下的文章
$articles = Articles::published()
->where('tid', $tid)
->where('delete_time', null)
->order('publish_date', 'desc')
->limit(8)
->select();
// 处理图片如果文章image为空则取分类的image
foreach ($articles as &$article) {
if (empty($article['image']) && !empty($article['cate'])) {
$category = ArticlesCategory::where('id', $article['cate'])
->where('delete_time', null)
->find();
if ($category && !empty($category['image'])) {
$article['image'] = $category['image'];
}
}
}
return json([
'code' => 200,
'msg' => 'success',
'list' => $articles,
]);
}
/**
* 获取上一篇下一篇
* @param int $id 文章ID
* @param int $cate 分类ID
* @return array
*/
private function getNextPreviousArticles(int $id, int $cate): array
{
$nextArticle = Articles::where('id', '<', $id)
->where('cate', $cate)
->where('delete_time', null)
->where('status', 2)
->field('id,title')
->find();
$previousArticle = Articles::where('id', '>', $id)
->where('cate', $cate)
->where('delete_time', null)
->where('status', 2)
->field('id,title')
->find();
return [
'code' => 200,
'msg' => 'success',
'next' => $nextArticle,
'previous' => $previousArticle,
];
}
/**
* 通过分类 ID 获取分类名称
* @param int $cateId 分类ID
* @return string
*/
private function getCategoryName(int $id): string
{
$categoryInfo = ArticlesCategory::where('id', $id)
->where('delete_time', null)
->find();
if (!$categoryInfo) {
return '未分类';
}
return $categoryInfo['name'];
}
/**
* 获取相关文章
*/
private function getRelatedArticles(int $id, int $cate): array
{
$articles = Articles::where('id', '<>', $id)
->where('cate', $cate)
->where('delete_time', null)
->where('status', 2)
->order('top', 'desc')
->order('recommend', 'desc')
->order('sort', 'desc')
->order('id', 'desc')
->limit(5)
->select();
foreach ($articles as &$article) {
$article['cate'] = $this->getCategoryName($article['cate']);
}
return [
'code' => 200,
'msg' => 'success',
'list' => $articles,
];
}
}