简体   繁体   中英

Inserting a list of complex objects to the database

In my application I'm going to have some list of a complex object I'm going to insert into a database.
The list is attached to a user, so I thought about adding a column with a list of IDs to the Users table, and then have the app convert the list back into complex objects using the list of IDs.

For example; A user have 3 Subjects IDs: "2,3,23" .
Each subject has a name, grade, etc...

On runtime, the app would go through each ID and get its properties from the database and add the complete subject to the list.

The problem is that sounds quite inefficient to be honest.
And therefore, my question is; is there a way to do it more efficiently?

The normal way to do this would be to have a separate table for the Subjects and that table has a UserID which is a foreign key back to the owning User record.

Then you don't have to mess about with editing a comma-separated string. It also allows you define a foreign-key constraint (as long as your DB can it) which will stop you from inserting a Subjects record with a UserID that doesn't exist in the User table.

To load the Subjects for a User, you just retrieve all the records from the Subjects table with the Id of the User.

If a many-to-many relationship is more appropriate, where a User can be linked to many Subjects and a Subject can be linked to may Users, then you would use a join table, say UserSubjectJoin which contains each UserID and SubjectID pairing. Again, this can have constraints to ensure that the IDs must exist in the Users and Subjects tables.

In this scenario, you need to join your UserSubjectJoin table to the Subjects table to retrieve all the Subjects records for the UserID you specify.

To answer your question fully, this would be more efficient because you don't have to maintain a column of strings in the Users table as you just add/delete rows from the Subjects table and the associations are automatically updated.

And if you actually have a many-to-many relationship, then under your initial design you would also need to have a column of UserIDs on the Subjects table which then doubles the maintenance, and risk of getting it wrong.

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