【问题标题】:Retrieving Data from Multiple tables duplicates and creates additional duplicate objects when grouping by从多个表中检索数据重复并在分组时创建额外的重复对象
【发布时间】:2022-11-22 17:25:53
【问题描述】:

我正在使用这个 foreach 通过搜索 DocketList 从 Orders 获取数据我得到了预期的数据,但它创建了额外的对象!

$spreadreport = [];
$getOrderList = DocketList::groupBy('order_list_id')->whereBetween('docket_date', $request->input('data'))->pluck('order_list_id');
foreach ($getOrderList as $listId) {
$getOrderId = OrderList::where('id', $listId)->pluck('order_id');
foreach ($getOrderId as $orderId) {
$spreadreport[] = Order::where('id', $orderId)->get()->groupBy('order_delivery_zone');
}

下面我附上了我目前获得的数据。按订单交付区域分组不应重复,因为它对于我搜索的两个数据都是相同的。我不明白为什么当我期待一个时我得到两个对象..订单269和270都应该在2组下 请帮忙!

【问题讨论】:

  • 你试过在get之前运行groupBy吗?试试这个代码$spreadreport[] = Order::where('id', $orderId)->groupBy('order_delivery_zone')->get();
  • 是的。我有一个语法错误!
  • 什么错误?
  • 这只是一个语法错误,伙计
  • 你能告诉我你输入了什么代码吗?你输入的是$spreadreport[] = Order::where('id', $orderId)->groupBy('order_delivery_zone')->get();吗?

标签: arrays laravel object foreach


【解决方案1】:

我已经解决了这个问题。 这是我的控制器。

 $getOrderList = DocketList::groupBy('order_list_id')->whereBetween('docket_date', $request->input('data'))->pluck('order_list_id');
            $getOrderId = OrderList::whereIn('id', $getOrderList)->pluck('order_id');
            $getProductListId = OrderListProducts::groupBy('order_list_id')->whereIn('order_list_id', $getOrderList)->pluck('order_list_id');
            $getOrderProductId = OrderList::whereIn('id', $getProductListId)->pluck('order_id');
            $orders = Order::whereIn('id', $getOrderId)->WhereIn('id', $getOrderProductId)->get();

并创建了一个关系产品来获取我想要的数据

   public function products()
    {
        $products = [];
        foreach ($this->order_list as $order_list) {
            foreach ($order_list->order_list_products as $product) {
                $products[] = $product->product_mix_id;
            }
        }

        return $products;
    }

【讨论】:

    猜你喜欢
    • 2015-09-16
    • 2012-09-16
    • 2022-07-20
    • 2017-05-07
    • 1970-01-01
    • 2014-11-26
    • 2021-12-03
    • 2020-10-29
    • 2015-10-17
    相关资源
    最近更新 更多