简体   繁体   中英

Update record in many-to-many linking table

I'm trying to figure out the best way of updating the linking table in a many-to-many relationship.

I have two entities: Artist and Skill.

The relationship between these two are many-to-many, given that an artist has 1 or 1+ skills and a skill can be possessed by 1 or 1+ artists.

What I would like to ask is the best practice of updating the records in the linking table.

Example: Assume an artist has the below skills artist_id: 1 skill_id: 1, 2, 3, 4

I'd like to edit the artist to have the below skills after a while. artist_id: 1 skill_id: 2, 3, 5, 9

My current practice of updating is to delete all the old records and then insert the new records in to the linking table.

I'm thinking if the best practice is actually compare two arrays ( select old records from the linking table and compare with the new ones) and then decide what to be added and what to be deleted.

Example: From the above case, decide the difference between [1, 2, 3, 4] and [2, 3, 5, 9]. That being said [1, 4] will need to be removed from the linking table and add [5, 9] to the linking table.

I'd like to know what's a better way to deal with this, thank you.

I'm using Node.js and MySQL. I've tried wiping all the old records first and then add the new records. I don't think this is the best practice so would like to know.

(A 'bridging table' is the usual name to support a many-to-many relationship, although there's many other names . 'Linking table' is too vague of a term: there's many ways some table might link to others.)

My current practice of updating is to delete all the old records and then insert the new records in to the linking table.

Don't do that.

I'm thinking if the best practice is actually compare two arrays

No that's not best practice. You are making this too hard.

  • If user input says Artist A has Skill S1 but the bridging table hasn't recorded that, insert it -- that is, insert a single row.
  • If user input doesn't say Artist A has Skill S2, but the bridging table does record that, delete it -- that is, delete a single row.
  • Deleting something is usually one of those actions you want to check with the user: are you sure? When they click Ok , delete the row. There's no need to think in terms of arrays or whole sets of records.

(Yes, what's held in tables is sets. But user transactions are usually row-at-a-time. In your scenario, it's not like an Artist will all-of-a-sudden learn to play the piano and juggle, and lose the ability to tap-dance. That is I'd guess, Skills are 'Slowly changing'.)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM