mdev11's avatar

Is it possible to update with column and variable using upsert?

Table:

id | quantity | product_id | user_id
1  |    1     |     1      |   1
2  |    4     |     2      |   1

I'm using upsert to insert or update bulk rows:

$products = [
    [
        'product_id' => 3,
        'quantity' => 2,
        'user_id' => 1,
    ],
    [
        'product_id' => 1,
        'quantity' => 8,
        'user_id' => 1,
    ]
];

Cart::upsert(
    $products,
    ['product_id', 'user_id'],
    ['quantity']
);

The above query results:

id | quantity | product_id | user_id
1  |    8     |     1      |   1
2  |    4     |     2      |   1
3  |    2     |     3      |   1

Is it possible to update the quantity with the old value + the new value instead of overriding it?

Desired result:

id | quantity | product_id | user_id
1  |    9     |     1      |   1
2  |    4     |     2      |   1
3  |    2     |     3      |   1
0 likes
1 reply
jdc1898's avatar

Yes. You can use the updateOrCreate() method to upset your data. You simply specify the field you want to check if it is the same. If they are the same, then it updates the defined fields. If it doesn't match, then it creates the record.

Please or to participate in this conversation.