Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQLite One-to-Many Relationship Set/Get Foreign Key

I am building an android app project with SQLite DB.

I got stuck on One-To-Many RelationShip.

This is One

private static final String createTableOrders =
        "CREATE TABLE " + TABLE_ORDER + "("
                + KEY_ID + " INTEGER PRIMARY KEY AUTOINCREMENT,"
                ...
                + KEY_COLUMN_FORMATS + " INTEGER REFERENCES " + TABLE_FORMATS + "(" + KEY_ID + ")"
                + ");";

This is Many

private static final String createTableFormats =
        "CREATE TABLE " + TABLE_FORMATS + "("
                + KEY_ID + " INTEGER PRIMARY KEY AUTOINCREMENT,"
                  ...
                + ");";

My problems is with set/get methods. Lets say that I would need to get list of ids of all Formats that are in one Order. I guess same thing goes for set method.

I tried to find this kind of question on SO but most of the question were just for SQL part.

P.S. Spent 3 hours trying to make it by myself but the only thing I got to was using GSON to code list of ids into String but it was just a dead-end.

EDIT: I need to get that information inside the code.

P.S.S I have been doing this for 18 hours so sorry if this is uber-stupid question.

like image 383
TheLibrarian Avatar asked Dec 20 '22 12:12

TheLibrarian


1 Answers

A one-to-many relationship requires the foreign key column in the "many" table:

CREATE TABLE Orders (
    ID PRIMARY KEY
);
CREATE TABLE Formats (
    ID PRIMARY KEY,
    OrderID REFERENCES Orders(ID)
);

To get all formats belonging to an order, you just look up rows with the ID of that order:

SELECT * FROM Formats WHERE OrderID = ?

In Jave:

Cursor cursor = db.query(TABLE_FORMATS,
                         new String[] { whatever columns you need },
                         "OrderID = " + orderID,
                         null, null, null, null, null);
while (cursor.moveToNext()) {
    // read one order from the cursor
}
cursor.close();
like image 100
CL. Avatar answered Dec 22 '22 03:12

CL.