Got a small relational problem with a project I'm working on, I've tried googling the answer, but not sure what terminology to use to find my answer Lol
The problem to be solved:
A user can have many photos, and one of these photos can be a profile photo, but only one.
So for example:
CREATE TABLE user (
ID Int NOT NULL AUTO_INCREMENT PRIMARY KEY,
username varchar(25) NOT NULL
);
CREATE TABLE photo (
ID Int NOT NULL AUTO_INCREMENT PRIMARY KEY,
user_ID Int NOT NULL,
imgpath varchar(260) NOT NULL,
FOREIGN KEY (user_ID) REFERENCES user (ID) ON UPDATE CASCADE
);
CREATE table userprofphoto (
user_ID Int NOT NULL,
photo_ID Int NOT NULL,
FOREIGN KEY (photo_ID) REFERENCES photo (ID) ON UPDATE CASCADE,
FOREIGN KEY (user_ID) REFERENCES user (ID) ON UPDATE CASCADE
);
So a query to get the users profile photo would be:
SELECT imgpath FROM photo WHERE photo_ID=(SELECT photo_ID FROM userprofphoto WHERE user_ID=:userid LIMIT 1)
This works, but it creates a relational loop. Should/Could I fix this?
I did think about removing the user_ID
from the userprofphoto
table, but then this would increase the query length:
SELECT imgpath FROM photo
LEFT JOIN userprofphoto ON userprofphoto.photo_ID=photo.ID
WHERE photo.user_ID=:user_id
Any help appreciated :D