Entity relationship consideratoin
If you don't share images between products (never use one image for more than 1 product) then your relationship is really One-To-Many and there is no need for products_images
junction table. This would simplify your model to:
- Products (id_product, ...)
- Images (id_image, ..., id_product)
And id_product
in Images
table would have a Foreign Key pointing at Products(id_product)
. That way, when you want to detach all images from a product you would simply run an update statement:
UPDATE images SET id_product = NULL WHERE id_product = ?
Sorting consideration
Since you need to save the order in which images are stored in the database, depending on what columns you have in Images
table you could use for example id_image
if it was declared as SERIAL
(auto-incremented integer value). As a rule of thumb in PostgreSQL (where there are no clustered indexes) remember that if you need the output sorted, you need to do that yourself (example: add an ORDER BY id_image
) at the end.