Suppose I have 2 database tables user
and topic
.
Users can have multiple topics, and a topic can have multiple users associated with it. It is a many to many relationship.
I have a user_id
PK in the user
table and a topic_id
PK in the topic
table.
I know I can enforce the many to many relationship by using a 3rd child table (call it linking_table
) which has a FK to the user_id
and a FK to the topic_id
.
Suppose I am OK with users being created at will, but I do not want someone to be able to create a topic without it being associated with a user. In other words, I want it such that a topic row should never exist without there being a row in the linking table which links a user to that topic. On the other hand, I also don't want there to be a row in linking_table
between a user and a topic which does not exist yet.
It seems I want it to be that you cannot insert a row into topic without also inserting a row into linking_table
at the same time.
Is this kind of constraint possible or even reasonable? Without this constraint, it would be possible to insert into the topic table, and not create a link in linking_table
at all.
Edit:
Something has occurred to me. It doesn't matter if a topic is created and not associated with a user. I will only be accessing backend data via a user, and the linking table is what will link a user to a topic, so even if theoretically there are topics not connected to users, it doesn't matter from any practical perspective. It's similar to a detached linked list node. Since it isn't referenced, it doesn't matter if it exists, assuming I do some sort of clean up on the table and remove any orphaned topics.