我在iOS应用程序中使用sqlite,我使用FMDB作为包装器.这是我的数据库架构:
CREATE TABLE Offer (code TEXT PRIMARY KEY NOT NULL,name TEXT); CREATE TABLE OffreMarket (codeOffer TEXT NOT NULL,codeMarket TEXT NOT NULL,FOREIGN KEY(codeOffer) REFERENCES Offer(code),FOREIGN KEY(codeMarket) REFERENCES Market(code)); CREATE TABLE Market (code TEXT PRIMARY KEY NOT NULL,name TEXT);
我的模型对象:
@interface Offer : NSObject @property (nonatomic,copy) NSString *code; @property (nonatomic,copy) NSString *name; @property (nonatomic,copy) NSArray *markets; @end @interface OffreMarket : NSObject @property (nonatomic,copy) NSString *codeOffer; @property (nonatomic,copy) NSString *codeMarket; @end @interface Market : NSObject @property (nonatomic,copy) NSString *name; @end
- (NSArray *)offers { // Open database NSMutableArray *offers = [NSMutableArray new]; FMResultSet *resultSet = [database executeQuery:@"SELECT * FROM Offer"]; while ([resultSet next]){ Offer *offer = [Offer new]; offer.code = [resultSet stringForKey:@"code"]; offer.name = [resultSet stringForKey:@"name"]; // Get the markets for each offer FMResultSet *marketResultSet = [database executeQuery:@"SELECT * FROM OffreMarket WHERE codeOffer = ?",offer.code]; NSMutableArray *offers = [NSMutableArray new]; while ([marketResultSet next]) { OffreMarket *offerMarket = [OffreMarket new]; .... [offers addObject:offerMarket]; } market.offers = [offers copy]; } return [offers copy] }