I want to delete the base product if the variant is attached to another base product and the original base product does not have any variants.
Example:
Product p1 has v1 and v2 as variants.
Now, v1 and v2 are attached to p2.
So, p1 has no variants now.
At this stage p1 does not has any variants at all, so p1 should be deleted.
I tried this with prepare interceptor on Variant. In this interceptor I checked if:
productModel.getVariants().isEmpty()
but here, it is giving false as the variant is still not removed (as the interceptor is called before removing the variant).
EDIT 1:
Now I am testing with:
productModel.getVariants().size() == 1
and this condition is working fine.
But, the problem is that:modelservice.remove(baseProduct) is still not working.
EDIT 2:
As suggested, I can't remove the base product before removing the variants, so now I am removing the variants first.
baseProduct.setVariants(CollectionUtils.emptyList());
modelservice.save(baseProduct);
modelservice.remove(baseProduct);
Problem is it's still not working.
EDIT 3:
I know why it's not working. Actually, I am setting the variants attribute in base product as null, but that is having no effect at all in the DB because its the variant that stores the primary key of base product in the attribute baseProduct.
Which brings me to square one. So, I have two different questions now:
How do I delete the base product if it's just become an orphan (original question)?
Why do we have a setVariants method at all, if it does nothing ?
EDIT 4:
Now that I know that interceptors just won't work, I am trying some alternate solution. Possible solutions:
Using the after save listener event.
Disadvantage: Using the after save listener, each time the product is saved will cause very high load on the server!
Creating a cronjob to remove all the orphan base products at the end of the day (just like Remove Empty Categories/Carts Cronjob).
Disadvantage: It might interfere with an otherwise normal product import process and delete the base products midway!
Which of the lesser evil should I choose. I am planning to go with #2.