You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
89 lines
2.8 KiB
89 lines
2.8 KiB
<?php
|
|
|
|
namespace App\Http\Controllers\Api\V1;
|
|
|
|
use App\Http\Resources\CategoreResource;
|
|
use App\Http\Resources\ProductResource;
|
|
use App\Models\Category;
|
|
use App\Services\PageServe;
|
|
use Illuminate\Http\Request;
|
|
use App\Http\Controllers\Controller;
|
|
|
|
class CategoryController extends Controller
|
|
{
|
|
/**
|
|
* 获取分类列表
|
|
*
|
|
* @param PageServe $serve 分页服务
|
|
* @return \Illuminate\Http\JsonResponse 返回分类列表的 JSON 响应
|
|
*/
|
|
public function index(PageServe $serve)
|
|
{
|
|
// 获取分页参数
|
|
list($limit, $offset) = $serve->getPageParameters();
|
|
|
|
// 构建分类查询
|
|
$query = Category::query();
|
|
|
|
// 根据名称过滤分类
|
|
if ($title = $serve->input('name')) {
|
|
$query->where('title', 'like', "%{$title}%");
|
|
}
|
|
|
|
// 获取总数和分类数据
|
|
$count = $query->count();
|
|
$categories = $query->orderBy('order')->limit($limit)->offset($offset)->get();
|
|
$categories = CategoreResource::collection($categories); // 转换为资源集合
|
|
|
|
return responseJson(200, 'success', $categories, compact('count')); // 返回成功响应
|
|
}
|
|
|
|
/**
|
|
* 获取指定分类下的产品
|
|
*
|
|
* @param PageServe $serve 分页服务
|
|
* @param int $category 分类 ID
|
|
* @return \Illuminate\Http\JsonResponse 返回产品列表的 JSON 响应
|
|
*/
|
|
public function getProducts(PageServe $serve, $category)
|
|
{
|
|
// 获取分页参数
|
|
list($limit, $offset) = $serve->getPageParameters();
|
|
|
|
// 排序的字段和排序的值
|
|
$orderField = $serve->input('order_field');
|
|
$orderValue = $serve->input('order_value');
|
|
|
|
// 查找指定分类
|
|
/**
|
|
* @var $category Category
|
|
*/
|
|
$category = Category::query()->findOrFail($category);
|
|
|
|
// 获取该分类下的产品查询
|
|
$query = $category->products();
|
|
|
|
// 根据名称过滤产品
|
|
if ($name = $serve->input('name')) {
|
|
$query->where('name', 'like', "%{$name}%");
|
|
}
|
|
|
|
// 获取排序的字段
|
|
$allFields = ['created_at', 'sale_count', 'view_count'];
|
|
$orderField = in_array($orderField, $allFields) ?
|
|
$orderField :
|
|
array_first($allFields); // 默认排序字段
|
|
$orderValue = $orderValue === 'asc' ? 'asc' : 'desc'; // 默认排序方式
|
|
|
|
// 获取数据
|
|
$count = $query->count(); // 获取产品总数
|
|
$products = $query->orderBy($orderField, $orderValue)
|
|
->limit($limit)
|
|
->offset($offset)
|
|
->get();
|
|
$products = ProductResource::collection($products); // 转换为资源集合
|
|
|
|
return responseJson(200, 'success', $products, compact('count')); // 返回成功响应
|
|
}
|
|
}
|