I have one function that I am not happy with, the function deletes a product from a table.
This also then deletes all categories, tags and variants of that product,
and for each variant deletes all its images, documents, and values.
This comes down to two select queries and six delete queries.
Is there a way I could make this less database intensive?
delete from $this->table where id = $id
delete from $this->clink where product_id = $id
delete from $this->tlink where product_id = $id
$variants = select id from $this->vlink where product_id = $id //e.g. (1,2)
delete from $this->vlink where product_id = $id
delete from cart_variant_values where variant_id in $variants
delete from cart_variant_images where variant_id in $variants
delete from cart_variant_documents where variant_id in $variants
I was hoping I could do something like:
variants = select id from $this->vlink where product_id = $id //e.g. (1,2)
delete from $this->table where id = $id
delete from $this->clink, $this->tlink, $this->vlink where product_id = $id
delete from cart_variant_values, cart_variant_images, cart_variant_documents
where variant_id in $variants
But obviously that doesn’t work!
Edit (21 Nov 2012):
Would this work?
DELETE vi, vv, vd, v, p, pc, pt
FROM cart_variant_images vi
INNER JOIN cart_variant_values vv
INNER JOIN cart_variant_documents vd
INNER JOIN cart_product_variants v ON vd.variant_id = v.id
INNER JOIN cart_products p ON v.product_id = p.id
INNER JOIN cart_products_categories pc ON p.id = pc.product_id
INNER JOIN cart_products_tags pt ON p.id = pt.product_id
WHERE p.id = $id;
That query throws me no errors, but I am wondering if it will do what I want?
Note that there will be different amounts of rows in each table, so is inner join the right join?
Use foreign keys with
ON DELETE CASCADE