如何管理Core Data中的一对多关系?(How to manage one-to-many relationship in Core Data?)
我很难搞清楚Core Data如何处理数据库的一些事情。 我将用一个具体的例子来解释我的问题:
我们只是说我们有以下架构,其中有部门拥有众多帐户(我们的地址)。
我使用编辑器创建了我的Core Data文件。 在CachedDepartment类中,我添加了必要的属性,并且我创建了一个to-many关系,并且我已经选择了“Inverse”到我的CachedAccount的Department属性.CacheAccount也有属性,并且关系与“解决“CachedDepartment的关系”。
我有以下来源(我给你2个头文件。其余的没有任何兴趣):
@interface CachedAccount : NSManagedObject { @private } @property (nonatomic, retain) NSNumber * accountID; @property (nonatomic, retain) NSString * email; @property (nonatomic, retain) NSString * name; @property (nonatomic, retain) CachedDepartment *department; @end @class CachedAccount; @interface CachedDepartment : NSManagedObject { @private } @property (nonatomic, retain) NSString * departmentID; @property (nonatomic, retain) NSString * departmentName; @property (nonatomic, retain) NSSet *addresses; @end @interface CachedDepartment (CoreDataGeneratedAccessors) - (void)addAddressesObject:(CachedAccount *)value; - (void)removeAddressesObject:(CachedAccount *)value; - (void)addAddresses:(NSSet *)values; - (void)removeAddresses:(NSSet *)values; @end
现在的问题是:
- 如何创建帐户和部门对象,以便建立一对多的关系?
- 我应该如何处理CoreDataGeneratedAccessors?创建之后,我应该调用CachedDepartment的-addAddressesObject函数,还是需要创建类似anAccount.department = aDepartment的东西,那就是它?
- 在创建对象的每种情况下,如何确保向部门添加地址不会创建地址的双重实例并存储它?我将不胜感激任何见解。
编辑:
是否应为CachedDepartment实体插入新对象,如下所示:
NSManagedObject *cachedDepartment= [NSEntityDescription insertNewObjectForEntityForName:@"CachedDepartment" inManagedObjectContext:[self managedObjectContext]]; /* set values for failedBankInfo here */ NSError *error; if (![context save:&error]) { NSLog(@"The following error occured: %@", [error localizedDescription]); }
然后将为cachedAccounts添加一条新记录,该记录将与新插入的cachedDepartment对象保持一对多的关系,如下所示:
NSManagedObject *cachedAccounts = [NSEntityDescription insertNewObjectForEntityForName:@"CachedAccounts" inManagedObjectContext:[<b>cachedDepartment managedObjectContext</b>]]; /* set values for failedBankInfo here */ //setting the one-to-many relationship [cachedDepartment addCachedAccountObject:cachedAccount]; [cachedAccount setCachedDepartment:cachedDepartment]; // NSError *error; if (![context save:&error]) { NSLog(@" couldn't save: %@", [error localizedDescription]);
I am having a hard time figuring out some things about how Core Data handles its database. I will explain my problems with a concrete example:
Let's just say that we have the following schema where there are departments which hold numerous accounts (our addresses).
I have created my Core Data file using the editor. In the CachedDepartment class, I have added the necessary attributes, and I have created a to-many relationship, and I have selected "Inverse" to the "Department property of my CachedAccount. CacheAccount also has attributes, and a relationship inverse to the "addresses" relationship of CachedDepartment.
I have the following sources (I give you the 2 header files. The rest contain nothing of interest):
@interface CachedAccount : NSManagedObject { @private } @property (nonatomic, retain) NSNumber * accountID; @property (nonatomic, retain) NSString * email; @property (nonatomic, retain) NSString * name; @property (nonatomic, retain) CachedDepartment *department; @end @class CachedAccount; @interface CachedDepartment : NSManagedObject { @private } @property (nonatomic, retain) NSString * departmentID; @property (nonatomic, retain) NSString * departmentName; @property (nonatomic, retain) NSSet *addresses; @end @interface CachedDepartment (CoreDataGeneratedAccessors) - (void)addAddressesObject:(CachedAccount *)value; - (void)removeAddressesObject:(CachedAccount *)value; - (void)addAddresses:(NSSet *)values; - (void)removeAddresses:(NSSet *)values; @end
And now the questions:
-- How should an account and department objects be created so that a one-to-many relationship will be established?
-- What should I do with CoreDataGeneratedAccessors?After creation, should I call the -addAddressesObject function of CachedDepartment or I will need to make something like anAccount.department = aDepartment and that's it?
-- In each case when creating objects how can I make sure that adding an address to a department won't create a double instance of the address and store it?I would appreciate any insights on this.
EDIT:
Should inserting new objects for CachedDepartment entity look like the following code:
NSManagedObject *cachedDepartment= [NSEntityDescription insertNewObjectForEntityForName:@"CachedDepartment" inManagedObjectContext:[self managedObjectContext]]; /* set values for failedBankInfo here */ NSError *error; if (![context save:&error]) { NSLog(@"The following error occured: %@", [error localizedDescription]); }
then would adding a new record for the cachedAccounts which will be in one-to-many relationship with the newly inserted cachedDepartment object be something like that:
NSManagedObject *cachedAccounts = [NSEntityDescription insertNewObjectForEntityForName:@"CachedAccounts" inManagedObjectContext:[<b>cachedDepartment managedObjectContext</b>]]; /* set values for failedBankInfo here */ //setting the one-to-many relationship [cachedDepartment addCachedAccountObject:cachedAccount]; [cachedAccount setCachedDepartment:cachedDepartment]; // NSError *error; if (![context save:&error]) { NSLog(@" couldn't save: %@", [error localizedDescription]);
原文:https://stackoverflow.com/questions/8723792
最满意答案
如果您看一下如何使用结构化束的最佳实践,您可以看到,这两种方法都很常见。 如果在同一供应商名称空间下有
Component
,Bridge
或任何其他库,则主要用于结构化的命名空间中的额外Bundle
。 例如symfony框架本身 。If you take a look at How to use Best Practices for Structuring Bundles you can see, both methods are common. An extra
Bundle
in the namespace if mostly used for structuring if you haveComponent
s,Bridge
s or any other libraries under the same vendor name space. E.g. like symfony framework itself.
相关问答
更多-
好吧,显然这个解决方案似乎正在工作: https : //github.com/KnpLabs/KnpMenuBundle/issues/122#issuecomment-6563863 Okay, apparently this solution seems to be working: https://github.com/KnpLabs/KnpMenuBundle/issues/122#issuecomment-6563863
-
Symfony 3 - Sonata Aplication Media Bundle错误(Symfony 3 - Sonata Aplication Media Bundle error)[2022-02-16]
您需要在composer.json中添加自动加载器定义,其方式与AppBundle 。 据我所知,新的bundle是在路径src/Application/Sonata/MediaBundle下生成的,所以它将是: "autoload": { "psr-4": { "AppBundle\\": "src/AppBundle" "Application\Sonata\MediaBundle\\": "src/Application/Sonata/MediaBundle" ... -
您应该使用Service Container使一些bundle功能在全局范围内可用。 然后,您可以通过$this->get('service.name');从控制器访问服务$this->get('service.name'); You should use Service Container to make some of bundle functions to be avaliable globally. Then you will can access to service from a control ...
-
与costum bundle symfony2中的命名空间的Typo错误(Typo error with namespace in costum bundle symfony2)[2022-07-02]
总结所有评论,你的TwitterOAuth.php必须是这样的:您应该使用依赖注入在您自己的bundle中完全实现此逻辑。 这意味着,不要劫持twig: config键,而是使用自己的bundle配置密钥。 在Bundles Container Extension中,您可以将配置值传递给容器参数,然后将这些参数作为构造函数参数传递给Twig Extension。 但是,在Alex已经指出将Twig Extension添加到容器之前,您需要检查Twig Bundle是否已加载并且可用。 http://symfony.com/doc/current/cookbook/tem ...我没有在SensionFrameworkExtraBundle中注册必要的AppKernel.php : new Sensio\Bundle\FrameworkExtraBundle\SensioFrameworkExtraBundle() 谢谢,@ pazi! I hadn't registered the essential SensionFrameworkExtraBundle in my AppKernel.php: new Sensio\Bundle\FrameworkExtraBundle\Se ...您误解了配置和参数。 如果要通过参数访问配置,则应根据配置设置参数: $container->setParameter('namespace', $config['namespace']); You misunderstood configuration and parameters. If you want access your configuration via parameters, you should set a parameter based on your configuration: $ ...Symfony Alice Bundle(Symfony Alice Bundle)[2022-06-29]
你尝试过current()吗? FM\AppBundle\Entity\Faq\Question: FaqQuestion_{1..100}: headline:body: position: category: @FaqCategory* Did you try with current() ? FM\AppBundle\Entity\Faq\Question: FaqQuestion_{1.. ... 可能是你必须在用户模式下使用ACL命令行(不是root) HTTPDUSER = ps axo user,comm | grep -E '[a]pache|[h]ttpd|[_]www|[w]ww-data|[n]ginx' | grep -v root | head -1 | cut -d\ -f1 ps axo user,comm | grep -E '[a]pache|[h]ttpd|[_]www|[w]ww-data|[n]ginx' | grep -v root | head -1 | cut - ...如果您看一下如何使用结构化束的最佳实践,您可以看到,这两种方法都很常见。 如果在同一供应商名称空间下有Component , Bridge或任何其他库,则主要用于结构化的命名空间中的额外Bundle 。 例如symfony框架本身 。 If you take a look at How to use Best Practices for Structuring Bundles you can see, both methods are common. An extra Bundle in the names ...相关文章
更多- 荐 通过Http管理Solr Core,实现索引的分类
- Hadoop core之IO
- Spring Data: a new perspective of data operations
- org.apache.solr.common.SolrException: No such core: core0
- merge solr index &&&&& very import create new core
- solr在Linux上配置多个core
- 自定义solr core
- 通过SolrJ 4.9管理Solr core
- Solr4.7.2启动时的Index locked for write for core问题分析
- 启动tomcat 报org.apache.catalina.core.StandardContext listenerStart
最新问答
更多- 获取MVC 4使用的DisplayMode后缀(Get the DisplayMode Suffix being used by MVC 4)
- 如何通过引用返回对象?(How is returning an object by reference possible?)
- 矩阵如何存储在内存中?(How are matrices stored in memory?)
- 每个请求的Java新会话?(Java New Session For Each Request?)
- css:浮动div中重叠的标题h1(css: overlapping headlines h1 in floated divs)
- 无论图像如何,Caffe预测同一类(Caffe predicts same class regardless of image)
- xcode语法颜色编码解释?(xcode syntax color coding explained?)
- 在Access 2010 Runtime中使用Office 2000校对工具(Use Office 2000 proofing tools in Access 2010 Runtime)
- 从单独的Web主机将图像传输到服务器上(Getting images onto server from separate web host)
- 从旧版本复制文件并保留它们(旧/新版本)(Copy a file from old revision and keep both of them (old / new revision))
- 西安哪有PLC可控制编程的培训
- 在Entity Framework中选择基类(Select base class in Entity Framework)
- 在Android中出现错误“数据集和渲染器应该不为null,并且应该具有相同数量的系列”(Error “Dataset and renderer should be not null and should have the same number of series” in Android)
- 电脑二级VF有什么用
- Datamapper Ruby如何添加Hook方法(Datamapper Ruby How to add Hook Method)
- 金华英语角.
- 手机软件如何制作
- 用于Android webview中图像保存的上下文菜单(Context Menu for Image Saving in an Android webview)
- 注意:未定义的偏移量:PHP(Notice: Undefined offset: PHP)
- 如何读R中的大数据集[复制](How to read large dataset in R [duplicate])
- Unity 5 Heighmap与地形宽度/地形长度的分辨率关系?(Unity 5 Heighmap Resolution relationship to terrain width / terrain length?)
- 如何通知PipedOutputStream线程写入最后一个字节的PipedInputStream线程?(How to notify PipedInputStream thread that PipedOutputStream thread has written last byte?)
- python的访问器方法有哪些
- DeviceNetworkInformation:哪个是哪个?(DeviceNetworkInformation: Which is which?)
- 在Ruby中对组合进行排序(Sorting a combination in Ruby)
- 网站开发的流程?
- 使用Zend Framework 2中的JOIN sql检索数据(Retrieve data using JOIN sql in Zend Framework 2)
- 条带格式类型格式模式编号无法正常工作(Stripes format type format pattern number not working properly)
- 透明度错误IE11(Transparency bug IE11)
- linux的基本操作命令。。。