1

i have an object to return like below : (the dd result)

Collection {#1421 ▼
  #items: array:2 [▼
    3943 => Collection {#1419 ▼
      #items: array:2 [▼
        0 => RoomPricingHistory {#923 ▼
          #fillable: array:19 [▶]
          #connection: "mysql"
          #table: "room_pricing_histories"
          #primaryKey: "id"
          #keyType: "int"
          +incrementing: true
          #with: []
          #withCount: []
          #perPage: 15
          +exists: true
          +wasRecentlyCreated: false
          #attributes: array:26 [▶]
          #original: array:26 [▼
            "id" => 4132
            "accommodation_room_id" => 3943
            "net_price" => null
            "board_price" => null
            "foreign_board_price" => null
            "sales_price" => 4200000
            "extra_bed_price" => null
            "half_charge_price" => null
            "half_board_price" => null
            "full_board_price" => null
            "foreign_net_price" => null
            "foreign_sales_price" => null
            "foreign_extra_bed_price" => null
            "foreign_half_charge_price" => null
            "foreign_half_board_price" => null
            "foreign_full_board_price" => null
            "operator_id" => 11
            "commission_percent" => null
            "foreign_commission_percent" => null
            "discount_percent" => 10.0
            "foreign_discount_percent" => null
            "from_date" => "2019-05-25 00:00:00"
            "to_date" => "2029-08-30 23:59:59"
            "is_deleted" => 0
            "created_at" => "2019-05-25 13:30:00"
            "updated_at" => "2019-05-25 13:30:00"
          ]
          #changes: []
          #casts: []
          #dates: []
          #dateFormat: null
          #appends: []
          #dispatchesEvents: []
          #observables: []
          #relations: array:1 [▶]
          #touches: []
          +timestamps: true
          #hidden: []
          #visible: []
          #guarded: array:1 [▶]
          #enableLoggingModelsEvents: true
          #oldAttributes: []
        }
        1 => RoomPricingHistory {#1042 ▶}
      ]
    }
    3944 => Collection {#1420 ▶}
  ]
}

and i have some mapped data like below :

Collection {#1422 ▼
  #items: array:2 [▼
    3943 => 8400000
    3944 => 400
  ]
}

now what i want to do is to return the mapped data which is the sum of price according to the id they have so the result of each item has the sum of price in it like below :

{
//room pricing history
 id:4132
room_id:3943
sum_of_prices :8400000
},
{
//room pricing history
 id:4133
room_id:3944
sum_of_prices :600
}

note : i am currently using resource but i dont know how to push the data in thier own object for example with this condition that they have the same id or something .

UPDATE :

here is my method :

  $from_date = $request->get('from_date');
        $to_date = $request->get('to_date');
        $acc_id = $request->get('acc_id');
        $room_price = [];
        $period = CarbonPeriod::create($from_date, $to_date);
        $dates = $period->toArray();
        $room_ids = AccommodationRoom::where('accommodation_id',$acc_id)->pluck('id')->toArray();
        for ($f = 0; $f < count($room_ids); $f++) {
            for ($i = 0; $i < count($dates); $i++) {


                /****************************************
                 * Looping for the Number of Rooms User Given
                 *****************************************/
                $room_price[] = RoomPricingHistory::with('accommodationRoom', 'accommodationRoom.roomCapacityHistoryLast')
                    ->where('accommodation_room_id', $room_ids[$f])
                    ->whereDate('from_date', '<=', $dates[$i])
                    ->whereDate('to_date', '>=', $dates[$i])
                    ->get()->sortByDesc('created_at')
                    ->take(1);
            }
        }
        $room = collect($room_price);
        $room_collection= $room->flatten();
        $sums = $detailed->mapWithKeys(function ($group, $key) {
            return [$key => $group->sum('sales_price')];
        });
        return RoomDetailResource::collection($room_collection);

6
  • Can you show us your code? Commented Dec 2, 2019 at 12:27
  • sorry i will update the code too Commented Dec 2, 2019 at 12:29
  • dont know what 'id' would be in this scenario Commented Dec 2, 2019 at 12:29
  • @lagbox its the Id of room which is the same for two of them but the problem might be that the room is in the relation of pricing object which can make it harder Commented Dec 2, 2019 at 12:31
  • 923 is not the 'id', it is a number assigned to the object internally in PHP, the #923 is an identifier internally, it is not part of your Model ... otherwise I dont know where you got the 923 number from Commented Dec 2, 2019 at 12:34

1 Answer 1

1

Based on the previous question where we worked out how to get the sums of the groups we can expand on that to include any additional data you would like and use map instead:

$new = $detailed->map(function ($group, $key) {
    return (object) [
        'id' => $group->first()->id,
        'room_id' => $key,
        'sum_of_prices' => $group->sum('sales_price'),
    ];
})->values();

We throw the values call on the end to reset the keys so the JSON output would be an array not an object, and your example output didn't seem to use keys. If you still want these objects keyed by 'room_id' don't call values.

Though I am not sure what you are actually trying to do since any API Resource you have is expecting particular data. You seem to want to mix arbitrary data into Eloquent Collections.

Sign up to request clarification or add additional context in comments.

1 Comment

This should be accepted answer. I totally missed he have array of price history in single item.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.