0

我在数据数组中得到响应,然后每个对象数组都有不同的数组,但我只想要一个包含所有对象的数据数组。这是我的代码。首先,我获取产品,然后将它们的过滤结果存储在一个数组中,然后使该数组唯一,然后发送此响应。我也尝试过直接发送值,但它仍然有父数组和子数组。还附上回复图片。

API 响应

API 响应

public function categoriesAndProducts(Request $request)
    {
        $marketId = $request->marketId;
        try {
            $this->categoryRepository->pushCriteria(new RequestCriteria($request));
            $this->categoryRepository->pushCriteria(new LimitOffsetCriteria($request));
            $this->categoryRepository->pushCriteria(new CategoriesOfFieldsCriteria($request));
        } catch (RepositoryException $e) {
            Flash::error($e->getMessage());
        }
        $products = DB::table('products')->where('market_id', $marketId)->groupBy('category_id')->get();
        //  return $products;
        $arr = [];
        foreach ($products as $product) {
            $arr[] = $this->categoryRepository->where('id', $product->category_id)->get();
        }
$values = array_unique($arr, SORT_REGULAR);
return $this->sendResponse($values, 'Categories retrieved successfully');
4

1 回答 1

0

我通过在 Product 和 Category 模型中创建关系然后使用with.

产品.php

public function category()
{
    return $this->belongsTo(\App\Models\Category::class, 'category_id', 'id');
}

分类.php

public function product()
{
        return $this->belongsTo(\App\Models\Product::class, 'category_id', 'id');
}

API控制器

$products = Product::where('market_id', $marketId)->where('deliverable', '!=', 0)->with('category')->groupBy('category_id')->get();
$categories = $products->pluck('category');
return $this->sendResponse($categories, 'Categories retrieved successfully');
于 2020-12-24T07:11:47.127 回答