I have 3 core data entities:
Entity A and Entity B and User which are related like
Entity A < ------ >> Entity B <<----- > User
I want to sort the entries in Entity A by the number of entries in entity B for that specific user.
I could do this:
fetch all Entity A entries
For each entry - fetch the number of Entity B entries for that entry and for the current user
Count the number of entries for that Entity A entry store and then sort.
This though seems awfully stupid.
Is there anyway i could sort Entity A with a NSSortDescriptor perhaps by using a Subquery?
Or if you know any other way i should solve this?
You can't sort on a collection operator so there is no way to us a sort descriptor to do what you want. Subqueries, like all predicates, simply find objects based on test, they don't sort them.
The easiest solution would be to add a transient attribute, say bCount, to EntityA. Then have the getter method return a count of related EntityB objects:
-(NSNumber *) bCount{
return [NSNumber numberWithInt:[self.bs count]];
}
Then sort your EntityA objects on the bCount key.
Related
I have an instance of the Department entity, which in turn has a relationship to the Employee entity via the 'employees' to-many relationship.
How would I construct my NSPredicate to return an array of employees within the specific department, in employeeNumber order, from this Department instance?
A predicate's purpose is to filter items, not to sort them. Use your fetch request's sortDescriptors property to determine how the results are sorted.
Alternatively, if you're accessing the relationship via the object's properties, use the NSSet method sortedArrayUsingDescriptors: to create a sorted array from the set of objects.
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.
Let say I have an entity user which has a one to many relationship with the entity menu which has a one to many relationship with the entity meal which has a many to one relationship with the entity recipe which has a one to many relationship with the entity element.
What I would like to do is to select the elements which belong to a particular user (username = myUsername) and particular menus (minDate < menu.date < maxDate).
Does anyone have an idea how to get them?
Thanks
You want to do a fetch on the element entity. From your description, it's not clear if you've defined the inverse relationships1 (e.g. element to recipie) and whether they are to-many or to-one. Assuming you have them defined and they are to-one, you can do your fetch with a predicate like [2]:
[NSPredicate predicateWithFormat:#"%# > recipe.meal.menu.date && recipie.meal.menu.date < %# && recipie.meal.menu.user.username LIKE[cd] %#", minDate, maxDate, myUsername];
I've used LIKE[cd] for a case-insensitive and diacritic-insensitive comparison on usename. Also note that Core Data stores dates as a double NSTimeInterval, without time-zone information. If you want to do timezone-sensitive date comparison, you're in for much more work.
1 If you haven't defined the inverse relationships, do it. As has been said many times elsewhere, Core Data is a graph management framework that just happens to be able to persist its graph to disk. It will do a lot of behind the scenes work to maintain referential integrity for you, automatically, if you define the inverse relationships. Particularly for many-to-many relationships, Core Data virtually requires the inverse to make things work.
[2] If you have defined to-many inverses where I've assumed to-one, you'll have to use a slightly more complicated predicate. The first clause, for example, would be
#"ANY (#unionOfSets.recipe.meal.menu.date) < %#"
(this last bit is untested; the KVO set operators are always a bit of experimenting for me). You can read up on the set and array KVO operators.
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.
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.