fixed category

This commit is contained in:
Edward Yang 2022-06-23 16:56:47 +08:00
parent 438ddb21ec
commit b0b4917b7d
2 changed files with 22 additions and 15 deletions

View File

@ -3,25 +3,20 @@
namespace Beike\Shop\Http\Controllers;
use Beike\Models\Category;
use Beike\Models\Product;
use Beike\Shop\Http\Resources\CategoryItem;
use Beike\Shop\Repositories\CategoryRepo;
use Illuminate\Http\Request;
use Beike\Shop\Repositories\CategoryRepo;
use Beike\Shop\Repositories\ProductRepo;
class CategoryController extends Controller
{
public function index(Request $request)
{
$items = CategoryRepo::list();
return CategoryItem::collection($items);
return CategoryRepo::list();
}
public function show(Request $request, Category $category)
{
$products = Product::query()
->with('description')
->latest()
->paginate();
$products = ProductRepo::getProductsBuilder($category)->paginate();
$data = [
'category' => $category,

View File

@ -13,6 +13,7 @@ namespace Beike\Shop\Repositories;
use Beike\Models\Product;
use Beike\Shop\Http\Resources\ProductList;
use Illuminate\Database\Eloquent\Builder;
class ProductRepo
{
@ -37,19 +38,30 @@ class ProductRepo
* @return array
*/
public static function getProductsByCategory($categoryId): array
{
$builder = self::getProductsBuilder($categoryId);
$products = $builder->get();
$items = ProductList::collection($products)->jsonSerialize();
return $items;
}
/**
* 获取 Builder
* @param $categoryId
* @return Builder
*/
public static function getProductsBuilder($categoryId): Builder
{
if (is_int($categoryId)) {
$categoryId[] = $categoryId;
}
$products = Product::query()
$builder = Product::query()
->select(['products.*', 'pc.category_id'])
->with(['description'])
->join('product_categories as pc', 'products.id', '=', 'pc.product_id')
->join('categories as c', 'pc.category_id', '=', 'c.id')
->whereIn('c.id', $categoryId)
->get();
$items = ProductList::collection($products)->jsonSerialize();
return $items;
->whereIn('c.id', $categoryId);
return $builder;
}
}