i've just started to use GreenRobot ORM and stacked with DB creation. I need to create N:M relation between two tables. Official doc. says they still dont support N:M, so I have to implement this by my own.
So, lets imagine I have 2 entities: Exercise and Accessories. They look like:
Entity accessories = schema.addEntity("Accessories");
accessories.addIdProperty();
accessories.addStringProperty("name").unique().notNull();
accessories.addStringProperty("desc");
Entity exercise = schema.addEntity("Exercise");
exercise.addIdProperty();
exercise.addStringProperty("name");
exercise.addStringProperty("desc");
exercise.addByteProperty("level");
And now I want to create another entity Exercise_Accessories, which contains ids of these entities above. How can I do it?
Thank you.
Yes you are right, that you must create a middle entity that holds references to the id's of the objects you want to link in N:M relationship.
Create an entity and get the properties of the id's:
Entity exerciseAccesories = schema.addEntity("ExercisesAccesories")
exerciseAccesories.addIdProperty();
Property exerciseId = exerciseAccesories.addLongProperty("exercise").getProperty();
Property accessoryId = exerciseAccesories.addLongProperty("accessory").getProperty();
And then link the properties:
accessories.addToMany(exerciseAccesories, accessoryId).setName("accessoryRef");
exercise.addToMany(exerciseAccesories, exerciseId).setName("exerciseRef");
Mead more about SQL as this is a standard way to model many-to-many relationships.
Of course this entity row is not added automatically to the database, when adding entity and accessory. You need to insert it manually.