Search code examples
arrayslaravelobjectforeach

Retrieving Data from Multiple tables duplicates and creates additional duplicate objects when grouping by


I am using this foreach to get data from Orders by searching the DocketList I am getting the expected data but it creates additional objects!

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

Below i have attached the data i get at the moment. The group by order delivery zone should not repeat as it the same for both the data i search. I don't understand why i get two objects when i am expecting one.. both order 269 and 270 should be under the group by 2 please help!

enter image description here


Solution

  • I have solved this issue. This is my controller.

     $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();
    

    and created a relationship products to get the data as i want

       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;
        }