【问题标题】:Getting an API response in single array having different objects在具有不同对象的单个数组中获取 API 响应
【发布时间】:2021-04-01 19:20:42
【问题描述】:

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

API Response

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');

【问题讨论】:

    标签: php arrays json laravel api


    【解决方案1】:

    我通过在 Product 和 Category 模型中创建关系然后使用 with 附加数据找到了解决方案。

    产品.php

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

    Category.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');
    

    【讨论】:

      猜你喜欢
      • 2018-05-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-03-28
      • 2022-11-17
      • 1970-01-01
      相关资源
      最近更新 更多