Heuristic
Heuristic

Reputation: 5341

Use class to represent foreign key / join table in Android SQLite?

I need to use classes to represent entities in database, here are some information:

=== TABLEs ===

SHOP shop_id(primary) name owner

FAVOURITES LIST fav_id(primary) list_name

(JOIN)FAV_SHOPS fav_id(primary) shop_id(primary)

If I use a class Shop to represent shop entity, and FavShops to represent fav_shops, FavShops is written as below:

class FavShop {
    int fav_id;
    String list_name;
    NSSet<Shop> shops;
}

Then how do I retrieve fav_shops from database in SQLite(Android)? I'll be appreciated if any one can provide some SQL statement, I also need to save the list to database, say, I added another shop to FavShop "My Favourites", how do I save it back to database?

Thanks!

Upvotes: 0

Views: 491

Answers (1)

BFil
BFil

Reputation: 13096

You can use JOIN to get your FavShops table..

SELECT * FROM fav_shops INNER JOIN favourites_list ON fav_shops.fav_id = favourite_list.fav_id WHERE favourite_list.fav_id = <YOUR_LIST_ID>

You can put whatever clause you need in your WHERE (shop_id = ?, list_name = ?, etc..)

And to insert a new row in the fav_shops table

INSERT INTO fav_sops (fav_id, shop_id) values ('My Favourites', <A_SHOP_ID>);

Upvotes: 1

Related Questions