建立不只单一的数据表
选择关联模式
编辑代码
1.第一种:一对一//数据库里面:一个表对应一个表的操作(一对一)
Car *car = [NSEntityDescription insertNewObjectForEntityForName:@"Car" inManagedObjectContext:app.managedObjectContext];
car.namee = @"BMW";
//插入数据
People *p = [NSEntityDescription insertNewObjectForEntityForName:@"People" inManagedObjectContext:app.managedObjectContext]; p.name = @"YY";
//关联people和car两个表
p.car = car;
//保存数据
[app saveContext];
//查询数据 //查询请求
NSFetchRequest *req = [[NSFetchRequest alloc] initWithEntityName:@"People"];
NSArray *result = [app.managedObjectContext executeFetchRequest:req error:nil];
//pp.car.namee 通过 查询people的数据,间接可以获得car的数据
for (People *pp in result) {
NSLog(@"%@---%@",pp.name,pp.car.namee);
}
////////////////////////////////////////////////////////////////////////////
2.第二种:一对多//对于一表对应多个数据表
//在创建时,一级类的.h文件中会出现四个带有二级类的方法,如下
//(Car *)- (void)addCarObject:(Car *)value
;- (void)removeCarObject:(Car *)value;
- (void)addCar:(NSSet*)values;
- (void)removeCar:(NSSet*)values;
//人车关联(关联people和car两个表)
//NSSet 集合 内部对象是无序的
[p addCar:[NSSet setWithObjects:car,car1,car2,car3, nil]];
//两种添加方式
[p addCarObject:car4];
//保存数据
[app saveContext];
//查询数据
//先找人 后找人的车
NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:@"People"];
NSArray *result = [app.managedObjectContext executeFetchRequest:request error:nil];
for (People *p in result) {
NSLog(@"People.name = %@",p.name);
}
People *pp = result[0];
for (Car *car in pp.car) {
NSLog(@"car.name = %@",car.name);
}
////////////////////////////////////////////////////////////////////////////
3.第三种:互相关联
//互相'赋值'
car.people = p;
p.car = car;
[app saveContext];
NSFetchRequest *req = [NSFetchRequest fetchRequestWithEntityName:@"People"];
NSArray *arr = [app.managedObjectContext executeFetchRequest:req error:nil];
//根据相互对应的关系,来间接查询另一张表的数据
for (People *p in arr) {
NSLog(@"%@--%@",p.name,p.car.name);
}