Core data many-to-many relationship - Predicate question - iphone

In my Core Data model I have two entities: List and Patient. List has an attribute called 'name'.
A List can have any number of Patients and each Patient can belong to any number of different lists. I have therefore set a relationship on List called 'patients' that has an inverse to-many relationship to Patient AND a relationship on Patient called 'lists' that has a to-many relationship to List.
What I'm struggling to figure out is how to create a Predicate that will select all Patients that belong to a particular List name.
How would I go about this? I have never used relationships before in Core Data.

This seems to work OK:
NSPredicate *predicate = [NSPredicate predicateWithFormat:#"(ANY lists == %#)", myList];
Where myList is an actual List entity.

Given a data model like:
List <<——>> Patient,
you can find all Patient instances that belong to a list with a particular name with a fetch request on the Patient entity using a predicate like:
[NSPredicate predicateWithFormat:#"ANY lists.name LIKE[cd] %#", listName]
assuming listName is an NSString instance with the list name you want. LIKE[cd] does a case-insensitive and diacritic-insensitive comparison.

It sounds like your data model is this:
List <<-->> Patient
I would think that if you know the particular list name, then you know the particular list object. If so, you can just grab the patients using the to-many relationship from List to Patient--it is a set of patient objects. For example, if the relationship from List to Patient is named "patients":
NSSet *patientSet = listObject.patients;
Note: this requires that you create subclasses for your managed objects so you can access the attributes and relationships as properties on your objects.
If you only know the list name for some reason, and you are fetching Patient objects, then you can create a predicate using the to-many relationship from Patient to List (assume it's named "lists" and the list's name in a string named "listName"):
NSPredicate *pred = [NSPredicate predicateWithFormat:#"ANY lists.name == %#",listName];

Ten years later, some more info !
Just some more info on the fantastic #GarryPettet answer,
Say you have entity CD_Person and aPerson is one of those. IE:
var aPerson: CDPerson
Say you have an entity CD_Pet
CD_Person has a relationship .pets which is a one-to-many CD_Pet
So just to be clear,
aPerson.pets
is indeed a Set of CD_Pet entities.
Almost certainly you'll have an id field which comes from your data source.
(Aside, .id must be an Int64 in your core data entity, even if it's a smaller int in your source data)
Two ways to go!
BOTH this
let p = NSPredicate(format: "(ANY pets == %#)", aPerson )
AND this
let p = NSPredicate(format: "(ANY pets.id == %lld)", aPerson.id)
... work perfectly, both are possibilities.
So there's two ways to go!
(PS: Don't forget the lld .. # won't work for Int64!)
Both work fine in the common situation where you have a "many-to-many" relationship.

Related

How do I set up an NSPredicate to check a relationship's attribute?

I have an entity called Entry, which has a one-to-many relationship with an entity called Media. The relationship name, from the Media side, is entry. Entry has an attribute named entryID, and I want to create a NSPredicate on media entities which returns all where their entry relationship has a particular entryID. How do I do this?
Assuming the relationship you want to fetch is called entry and entryID is some kind of number type.
NSNumber *desiredID = #(12345);
NSPredicate *predicate = [NSPredicate predicateWithFormat:#"entry.entryID = %#", desiredID];

Core data cross referencing two relationships

I have a data structure in Core Data like so...
User
Item
Category
User has a toMany relationship "FavouriteItems" to the Item entity.
Category also has a toMany relationship "Items" to the Item entity.
The user can select favourite items from any categories they wish. At the moment I am listing all the items and then displaying the Category alongside.
What I'd like to do is display all the user's favouriteItems for a selected Category.
i.e. select all the Items that have a relationship with Category x and User y.
I'm currently doing this by getting all the Items through one relationship (i.e. User.favouriteItems) and then filtering the NSSet using a block predicate.
Is it possible though to do this with a simple CoreData predicate?
Hmm... thinking about it would a predicate like this work...
[NSPredicate predicateWithFormat:#"interestedUser.id = %# AND category.id = %#", user.id, category.id];
And then run a fetch request on the item entity?
Would that work?
Shooting pretty blind as that's an awkward scenario to set up just to answer a question but perhaps
If you are filtering an array of Items which has the correct inverse relationships set up.
[NSPredicate predicateWithFormat:#"%# IN interestedUsers AND %# IN categories",
someUser,
someCategory];
Basically the Item has many users (interestedUsers) so we are saying is our user in this collection.
Similarly the Item has many categories (categories) so we are saying AND is our chosen category in this collection.

CoreData sort on to-many relationship

I'm writing an iOS app which has store of person records, and needs to display lists them sorted in particular ways. There are a variable number of these orderings, and they are generated on the fly, but I would like them to be stored in the datastore. The SQL way to do this is to have a ListPositions table with a list name, an id into the persons table, and a sort key. Then, to display a particular list, I can select all list ListPositions with a given name, pull in the referenced persons, and sort on the sort key. Trying to do this in CoreDatat, however I run into problems. I am trying to do this using a schema like:
Person:
Name
DOB
etc...
positions -->> ListPosition
ListPosition:
listName
sortKey
person --> Person
Then, I can get all the Persons in a given list with the NSPredicate
[NSPredicate predicateWithFormat:#"ANY positions.listName like %#", someList];
This allows me to dynamically add lists against a large set of Persons. The problem is that I am unable to use the sortKey field of ListPosition to sort the Persons. What NSSortDescriptor will do this? And if it is not possible to sort a fetch on the property of one element of a to-many relationship, what is another way to get multiple, dynamic orderings in coredata? I am displaying the lists with a NSFetchedResultsController, so I can't put the lists together myself in memory. I need to do it with a single NSFetchRequest.
You're right-- following a to-many relationship returns an NSSet, which has no inherent sorting. To get sorted results there are a couple of options:
Assuming that Person/ListPosition is a two-way relationship, do a new fetch request for ListPosition entities. Make the predicate match on the "person" relationship from ListPosition, which would look something like [NSPredicate predicateWithFormat:#"person=%#", myPerson]. Use whatever sort descriptor you need on the fetch request.
Follow the relationship as you're doing, which gives you an NSSet. Then use NSSet's -sortedArrayUsingDescriptors: method to convert that to a sorted array.
I think the best approach in this case would be to fetch on ListPosition entity instead. Add the sort Descriptor for sortKey (it would work in this case because the fetch request is on ListPosition entity) and prefetch the Person associated with the the list name using setRelationshipKeyPathsForPrefetching for "person" on the fetch request.
[NSPredicate predicateWithFormat:#"listName like %#", someList];
If I understand your model correctly, each Person has one ListPosition for each list in which it participates. Let's say we have acsending list by their names, so X people have X list positions with the same listName and sortKey.
I would create entity List, that would contain the sortKey attribute and then use it in sort descriptor.
entity List:
- sortKey : string
- ascending : bool
Create sort descriptor and use it in fetch request:
[NSSortDescriptor sortDescriptorWithKey:chosenList.sortKey ascending:chosenList.ascending];
Then you may have as many Lists as you want and you can easily use its sort key to sort all people.
If you want to store the positions in database (you didn't mention attribute index in your ListPosition, or anything similar), you can create “joint entity”:
entity PersonInList:
- index : integer
- person -> Person
- list –> List
Another idea is having ordered set of Person objects directly in List entity.
Get the ListPosition (it will come as a NSMutableSet). Then do a sort on the Set, like this:
NSMutableSet *positionsSet = [personEntity mutableSetValueForKey:#"positions"];
NSSortDescriptor *sortDescriptor = [NSSortDescriptor sortDescriptorWithKey:#"yourSortKey" ascending:NO];
NSArray *positionsSortedSet = [positionsSet sortedArrayUsingDescriptors:[NSArray arrayWithObject:sortDescriptor]];
That will give you a sorted out array according to your key.
I usually add an index field (type NSNumber) to an entity. It's very easy to calculate index in adding item. just by
object.index = person.positions.count
so, actually you don't need positions field but positions relationship. connect person entity to ListPosition entity would be enough.

Core Data - Breaking A Relationship

I have a Patient entity and a List entity. A Patient can belong to several different lists and a list can have several different patients.
Say I have a patient who belongs to 3 lists (A, B, C). I want to remove the patient from lists A & B. I do not want to delete lists A & B themselves though obviously. How do I go about doing this?
While Tim's answer above is technically correct, it seems like quite a bit of code to me.
I would assume that to remove a patient from the list, you already know that list and have a reference to it at the time you want to remove the patient. Therefore, the code can be as simple as:
id myPatient = ...;
id myList = ...;
[[myPatient mutableSetValueForKey:#"lists"] removeObject:myList];
This is of course assuming that your relationships are bi-directional. If they are not then I strongly suggest you make them bi-directional.
Lastly, because this is a many to many relationship, you can execute the above code in either direction.
[[myList mutableSetValueForKey:#"patients"] removeObject:myPatient];
update
Then the code is even simplier:
[myPatient setLists:nil];
That will remove the patient from all lists.
So in order to model this relationship, you have a many-to-many relationship between Patient and List. Let's say that in Core Data, this is represented by a patients relationship on List, with the inverse lists relationship on Patient. Furthermore let's assume that List has some property name with the name of the list, as an NSString.
In order to "break" the relationship (remove a Patient from some Lists), you'll have to have a reference to the Patient NSManagedObject that is to be removed, and the Lists you want to remove that Patient from. Then, all that remains to be done is get a mutable set of the patients for each list, and remove the desired patient:
// Assuming you have some PatientManagedObject *patient:
NSSet *patientLists = [patient lists]; // Set of ListManagedObjects
for(ListManagedObject list in patientLists) {
if([[list name] isEqualToString:#"A"] || [[list name] isEqualToString:#"B"]){
// Now you have to build the set of patients without this patient
NSMutableSet *listPatients = [list mutableSetValueForKey:#"patients"];
[listPatients removeObject:patient];
}
}
For more data, see the relevant Core Data documentation.

How to setup NSPredicate and NSEntityDescription in Coredata to do complicated SQL query

I know how to create NSPredicate to do sql like "SELECT * FROM DRINK". But how about this query:
"SELECT I.name, D_I.amount
FROM DRINK_INGREDIENT D_I, DRINK, INGREDIENT I
WHERE D_I.drinkID=1 AND DRINK.drinkID=1 AND I.ingredientID = D_I.ingredientID;"
How do I even set the NSEntityDescription, and NSPredicate for this kind of query?
Typically with Core Data you will design and use a data model that meets your needs. You should not think about it in terms of SQL--it does not even have to use SQL for storage--nor should you try to directly translate a SQL query into a fetch request with a predicate, etc.
That said, it can sometimes be helpful to think in terms of SQL WHERE clauses when building predicates, but really fetch requests comes down to what entity you need to get and how the collection should be filtered and/or sorted, etc.
Fetch requests are limited to a single entity, so I think you would need multiple fetch requests to simulate your query.
What does your Core Data data model look like? What are you trying to accomplish? What have you tried so far?
UPDATE
It sounds like your data model includes two entities: Drink and Ingredient with a many-to-many relationship between them:
Drink <<-->> Ingredient
Note that in Core Data, there is no DrinkIngredient entity unless you explicitly create it (there is an additional table for the many-to-many relationship, but it's abstracted away from you). Since you want an amount value associated with the rows in the additional table, I would recommend adding a DrinkIngredient entity in Core Data:
Drink <-->> DrinkIngredient <<--> Ingredient
Note: a DrinkIngredient has exactly one Drink and one Ingredient. Drinks can have many DrinkIngredients and Ingredients can be used by many DrinkIngredients.
It sounds like you want to get the name and amount for the list of ingredients for a particular drink. To do this, simply fetch DrinkIngredient objects with a filter predicate like this:
// assuming "aDrink" is a reference to a particular Drink object
// and "drink" is the relationship from DrinkIngredient to Drink
fetchRequest.predicate = [NSPredicate predicateWithFormat:#"drink == %#",aDrink];
// if the fetch request result array is named "ingredientList"
// and the relationship from DrinkIngredient to Ingredient is "ingredient"
for (DrinkIngredient *di in ingredientList) {
NSString *ingredientName = di.ingredient.name;
NSUInteger amount = di.amount.integerValue;
// use "ingredientName" and "amount" here
}
Since you are using Core Data and not SQL, you do things differently. For example, if you wanted to display an ingredient list with name and amount for all drinks, you would simply fetch all Drink objects (no filter predicate) and you access the ingredients through the relationship from Drink to DrinkIngredient.
Again, you should think about what you are trying to accomplish and design and use your data model appropriately. You should not think about SQL or queries.