INSERT and UPDATE in relationship n: m in MySQL

0

I need to create a relationship n: m in mysql, follow my example:

I have a table named empresas and another representantes . A company can have more than one representative, and one representative can belong to more than one company. In this case, the best relationship that fits into this problem is the n: m relationship.

In the n: m relationship, there is a third table joining the rep and a company. How can I make an INSERT and UPDATE in this third table recursively, without duplicating the records, knowing that when registering a company, I have several representatives, and vice versa?

    
asked by anonymous 15.01.2016 / 13:43

1 answer

2

I do not know if I understood the need well, but I think it would be:

insert into empresas_has_representantes (empresas_id, representantes_id) values (<id da empresa>, <id do representante>)

The way this data persists depends a lot on what you are using to manage your data access layer.

In hibernate, for example, there is a kind of relationship @ManyToMany that treats this for you automatically. Something about you here

If you use pure JDBC, or pure database access, you need to iterate your data and handle it manually using the query I posted above to put the relationships.

Obviously before the relationship persists, you need to persist with the companies and / or representatives.

As far as duplicity, you can guarantee via bank, inserting a unique constraint of the two columns. More information here

    
15.01.2016 / 15:41