Reputation: 501
I think this is simple but i can't find answer for me. I have two tables. Contacts and messages. Like this:
And my relationships are in contacts
And in Messages
I need take SQL: SELECT contacts.nickName, messages.id, messages.message FROM messages JOIN contacts.ccNumber = messages.senderCcNumber
My code for now getting a all data from Messages but i don't know how to join table Contacts to this fetch.
let appDel: AppDelegate = (UIApplication.sharedApplication().delegate as! AppDelegate)
let context: NSManagedObjectContext = appDel.managedObjectContext
let request: NSFetchRequest = NSFetchRequest(entityName: "Messages")
request.returnsObjectsAsFaults = false
request.predicate = NSPredicate(format: "senderCcNumber = %@", argumentArray: ["\(senderID)"] )
request.sortDescriptors = [NSSortDescriptor(key: "added", ascending: true)]
do { resultsMessagesList = try context.executeFetchRequest(request) } catch {}
print(resultsMessagesList)
return resultsMessagesList
Can someone give me a hint ?
Upvotes: 1
Views: 390
Reputation: 77641
CoreData is not a database. You don't need to join any tables (there are no tables).
You shouldn't be storing any foreign keys either.
Once you have a message
you can get the contacts
array by using message.contacts
. You don't need to execute any fetch requests to do this. (Other than to get the message in the first place).
Also, your entities should have singular names (Contact
not Contacts
).
If your messages have a sender and a receiver then create two relationships one called sender
and the other called receiver
and connect them to the Contact
entity.
I'd recommend investing in a CoreData basics book. Or there are some very good tutorials online. You would be saving yourself time in learning to use CoreData properly.
Upvotes: 1