For example: I have a "history" table with a foreign key that might point to different tables/entities depending a field value.
Table history:
create table history(
id int PimaryKey AUTO_INC,
elementid int, (ForeignKey)
elementtype varchar
)
this table is populated for example:
id ElementId ElementType
1 1 Device
2 2 Simcard
3 2 Simcard
this tells we have
the goal is to have a table that might be used for multiple entities.
Is this the correct way to integrate an dynamic foreign key? What I also thought of was for creating an list with tables/entities to refer to So the table then would look like:
ALTER TABLE history MODIFY ElementType INTEGER;
ElementType would refer to:
create table entities(
id int PimaryKey AUTO_INC,
name varchar
)
the new table history is populated for example:
id ElementId ElementType
1 1 1
2 2 2
3 2 2
The entities table is populated for example:
id name
1 Device
2 Simcard
A foreign key joins a table to another table by referencing its primary key. A foreign key constraint specifies that the key can only contain values that are in the referenced primary key, and thus ensures the referential integrity of data that is joined on the two keys.
The error message itself showing there is a foreign key constraint error, which means you are deleting a parent table where the child table contains the Primary table identifier as a foreign key. To avoid this error, you need to delete child table records first and after that the parent table record.
A Foreign Key always refers to a Unique Index or Primary Key. So the "one" side is always the one where the related columns are a key.
A Foreign Key is a link between two tables that is used to enforce referential integrity in the RDBMS. When the FK constraint is added to an existing column or columns in the table, It must be validated by the RDBMS before accepting any kind of modification on the table.
The proper way to implement dynamic FKs is to not do it.
Here are the reasons why, and what to do instead.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With