I have a basic data model that I want to implement in MySQL. I will be using mysqldb and SQLalchemy to do the data part, taking some data from some XML.
I’m not really sure how to implement what I want to do, and I wondered if anyone could point me in the right direction.
I have a few tables, and each table holds a section of the data.
Table 1 - recordTitle, recordID, recordDate
Table 2 - recordProp1, recordProp2, recordProp3
Table 3 - recordPropA, recordPropB, recordPropC
All the tables are unique in their own space, but T1 can have many T2s and T3s, and T2/T3 can belong to many T1s. Make sense?
I figured the way to resolve this was to have a 4th table:-
Table 4 – T1ref, T2ref, T3ref
and have a new colunm in T1-3 that is called TnRef and is basically a primary key for that table.
- Does this sound like a sensible approach?
- I figured when populating the data, I need to check each table entry for uniqueness, if it is, I capture the TnRef value, and if its isnt I insert the new row and collect the TnRef value after that. Once I have the value I can populate the T4 row that links everything together.
- Is ORM the right tool to do this?
For a many-to-many relationship like you described, yes I think it makes sense to have a fourth table linking T1 records with T2(s) and T3(s). I think you’ll want to add a key column to T2 and T3 though, to enable T4 to store the links correctly.
I assume you mean that T2 and T3 will be expanding, and that your application will be fielding requests to (for example) add { recordProp1= someval, recordProp2= someotherval } to a given record in T1. If so, then yes, you would want to do the lookup on T2 first, then insert it into T4 based on the keys of T1 and T2.
I think ORM is absolutely the right tool to do this. You’ll want to make sure all the foreign key relationships are correct in MySQL first, of course. But SqlAlchemy can handle many-to-many relationships. Take a look: http://docs.sqlalchemy.org/en/latest/orm/relationships.html#many-to-many