Question

Im not sure if is correct to have 3 self-references or if there is some othe way to confront this scenario.

I have a table/entity "Animal" (with all kind of basic fields like id, name, description...) and i want to represent that a specific animal (a dog for example):

"loves" some animals (lets say... tortoises and cows) "hates" some other animals (cats, chickens) and "is neutral" with other animals (pigs and horses)

The only possible way i see of modelling this schema is like in the picture. The 3 relations are many to many (NM) so i end up creating 3 more tables to store the relations between animals

enter image description here

There is a better way to represent the scenario? Am i missing something or doing something wrong?

Was it helpful?

Solution

You could model it the way I describe below which only takes three tables and would allow you to have conditions like "Dogs hate cats" but "Cats love dogs".

animals
    id              unsigned int(P)
    name            varchar(10)

+----+----------+
| id | name     |
+----+----------+
|  1 | dog      |
|  2 | cat      |
|  3 | cow      |
|  4 | tortoise |
|  5 | chicken  |
|  6 | pig      |
|  7 | horse    |
| .. | ........ |
+----+----------+

animals_feelings
    id              unsigned int(P)
    source_id       unsigned int(F animals.id)
    feeling_id      unsigned int(F feelings.id)
    target_id       unsigned int(F animals.id)

+----+-----------+------------+-----------+
| id | source_id | feeling_id | target_id |
+----+-----------+------------+-----------+
|  1 |         1 |          2 |         2 |
|  2 |         1 |          1 |         3 |
|  3 |         1 |          1 |         4 |
|  4 |         1 |          3 |         6 |
|  5 |         1 |          3 |         7 |
| .. | ......... | .......... | ......... |
+----+-----------+------------+-----------+

feelings
    id              unsigned int(P)
    description     varchar(10)

+----+-------------+
| id | description |
+----+-------------+
|  1 | loves       |
|  2 | hates       |
|  3 | is neutral  |
| .. | ........... |
+----+-------------+
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top