Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Updating an embedsMany child directly #2618

Unanswered
chrispage1 asked this question in Q&A
Discussion options

Hi,

I've got a database of products and each product has multiple variants. A variant is also a Product model. There are about 2000 products, and 3000 variants.

Periodically, I'm having to loop through the data and update stock values. We get a stock spreadsheet with SKU and corresponding stock values.

To get the relevant model, I'm performing the below:

$model = $this->provider->products()
 ->where('sku', $sku)
 ->orWhere('variants.sku', $sku)
 ->select(['_id', 'sku', 'variants._id', 'variants.sku'])
 ->first();
 
$model->variants->firstWhere('sku', $sku)?->setStock($stock) ?? $model->setStock($stock);

The problem is, ideally I'd like my query to return the child itself, but in all cases it'd still return the parent and then I'd have to drill down into the variants making the process very inefficient. Is there any way I am able to make this more efficient by querying the variants directly?

Chris.

You must be logged in to vote

Replies: 1 comment 1 reply

Comment options

Do you need to retrieve the model data or can you update the database directly?

This can be done with 2 queries

// Update the document where sku matches in the root document
YourModel::where('sku', $skuToUpdate)
 ->update(['stock' => $newStockValue]);
// Update the document within the "variants" array
YourModel::where('variants.sku', $skuToUpdate)
 ->update(['variants.$.stock' => $newStockValue]);

But I think it's possible to combine them using the $set aggregation pipeline with $cond.

You must be logged in to vote
1 reply
Comment options

I was only pulling the record so I could compare the SKU. Great, I didn't know you could do variants.$.stock, I'll give that a go - thank you! And I presume $ will only update the variant that matches that SKU?

But I think it's possible to combine them using the $set aggregation pipeline with $cond.

Being my first time using MongoDB, this one goes a little over my head but I'll take a look!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
Converted from issue

This discussion was converted from issue #2617 on September 13, 2023 17:43.

AltStyle によって変換されたページ (->オリジナル) /