Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to have an dynamic foreign key, and what is the best/correct to do so?

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

  • 1 record for entity of type "Device" with id "1"
  • 2 records for entity of type "Simcard" with id "2"

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
like image 634
Ismail Avatar asked Mar 13 '14 08:03

Ismail


People also ask

What is the correct foreign key constraint?

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.

How do I fix foreign key constraint failure?

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.

Which way should the foreign key go?

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.

What is a foreign key Why and when should we put a foreign key in a table can a table have many foreign keys?

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.


1 Answers

The proper way to implement dynamic FKs is to not do it.

Here are the reasons why, and what to do instead.

like image 185
Branko Dimitrijevic Avatar answered Sep 27 '22 23:09

Branko Dimitrijevic