0

I have a 2d array input like this:

[ 6 => [ [2=>3, 5=>7] ],
  8 => [ [1=>4, 9=>3] ],
  .....
]

The 6,8 are locationIDs and 2,5,1,9 are variantIDs and 3,4,7,3 are their respective quantities. I have to loop through the 2d array and get the data. The table has the fields location_id, variant_id and quantity.

    $variantsData  = self::where(function ($query) use ($inventoryData) {
        foreach ($inventoryData as $location => $variantData) {
            foreach ($variantData as $variant => $quantity) {
                $query->orWhere(function ($query) use ($location, $variant) {
                    $query->where('location_id', $location)
                        ->where('variant_id', $variant);
                });
            }
        }
    })->get();

The $inventoryData is the 2d array. I get the data required in this code but now I need to update the quantity by adding the stored quantity with this one in the array.

Saeesh Tendulkar
  • 638
  • 12
  • 30
  • I'm pretty sure you cannot do this with Eloquent, but there is already a question about [Updating multiple rows with different values in MySQL](https://stackoverflow.com/questions/25674737/mysql-update-multiple-rows-with-different-values-in-one-query). – Namoshek Apr 10 '19 at 05:11

1 Answers1

1

If I understand correctly, you want to execute a query where location_id = $location and variant_id = $variant correct? If so, instead of using multiple where clauses, you can pass a nested array in the one where clause.

i.e.

$query->where([
    ['location_id', $location],
    ['variant_id', $variant]
]);

Reference: https://laravel.com/docs/5.8/queries#where-clauses

Michael Peng
  • 806
  • 9
  • 11