R
R
Roman Sokharev2014-07-18 15:07:31
MySQL
Roman Sokharev, 2014-07-18 15:07:31

How to solve the problem with two foreign keys?

There is a table with elements of the form:

elements
-------------------------------
 `element_id `  | `someData`
-------------------------------
       1        |   blabla
 ------------------------------
       2        |  blablaAgain
-------------------------------

There is a table expressing relationships between elements (if any)
relations
------------------------------------------------
 `element_1_id` |  `element_2_id` |  `relation`

As planned, both elements (element_1_id and element_2_id) should be linked by foreign key to the `elements.element_id` field
. But the "muscular guy" said that it was absolutely impossible to do this (two fields by foreign key to one table).
How to be? Thank you.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
K
KoiGva, 2014-07-18
@koigva

An auxiliary table is needed to implement the ManyToMany relationship. If the relationship is OneToMany, you can get away with adding a field of type parent_id to the existing table.

M
Melkij, 2014-07-18
@melkij

I understand that this is M:M. The relation field is related to the connection itself, some additional data.
Two keys and hang:

ALTER TABLE `relations`
  ADD CONSTRAINT `relations_id1_fk` FOREIGN KEY ( `element_1_id`) REFERENCES `elements` (`element_id`),
  ADD CONSTRAINT `relations_id2_fk` FOREIGN KEY ( `element_1_id`) REFERENCES `elements` (`element_id`);

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question