Core Data Code for SQL Expression
I have an entity "booking" with the attributes "name" and "value". Now i would like to have a list of names ordered by the count of entities having this name. In SQL this would look like:
SELECT name, COUNT(name) AS nameCount
FROM booking GROUP BY name ORDER BY nameCount开发者_如何学Python
I am not able to find any solution to write that with NSSortDescriptor and NSPredicate for Core Data.
Anyone out there able to tranfer this to Core Data?
With a single "booking" entity, your "name" is repeated for multiple records. You could create a separate "name" entity containing just the name along with a to-many relationship to a "booking" entity containing just the "value". You would also want an inverse relationship (not to-many) from the "booking" entity back to the "name" entity. With that in place, you could use @count to get the number of "booking" records for each name.
If the to-many relationship was called "bookings", you could sort or select based on "bookings.@count".
Hope this helps!
精彩评论