laravel-mongodb icon indicating copy to clipboard operation
laravel-mongodb copied to clipboard

How to update an array inside an array?

Open jsivil-venngage opened this issue 2 years ago • 1 comments

I have a PurchaseRequest (like a Cart) and inside I have products...


{
    "id": "62862f04375eed096c6abc32",
    "products": [
        {
            "id": "628667dccee1aa7afe760d24",
            "currency": "MXN",
            "unit_cost": 10,
            "product_id": 1,
            "quantity": 1,
            "metadata": []
        }
    ]
}

I am not able to update just the position 0 of the array products.

I tried with:

$purchaseRequest->update(['products' => [$currentProductIndex => $currentProduct]]);

But this replaces the whole products.

I tried with:

$purchaseRequest->update(['products.' . $currentProductIndex => $currentProduct]);

But it doesn't do anything.

jsivil-venngage avatar May 20 '22 16:05 jsivil-venngage

I've solved it by debugging but I came across another bug...

PurchaseRequest::where(
    [
        ['_id', '=', new ObjectId($purchaseRequestId)],
        ['products.id', '=', $productId]
    ]
)->update(
    [
        '$set' => [
            "products.$" => $currentProduct,
        ]
    ]
);

I am using the timestamps for update, created and deleted and it is causing the following error, setting $set inside $set

src/Query/Builder.php

image

image

So I had to remove the $set inside my update statement, and leave only products.$

JorgeSivil avatar May 23 '22 02:05 JorgeSivil