I've got two Objects:
Account: Object {
dynamic var id: String?
dynamic var name: String?
dynamic var valid: String?
}
Transaction: Object {
dynamic var id: String?
dynamic var desc: String?
dynamic var accountId: String?
}
What I'm trying to do is somehow link the two objects so when I do a query on the transactions "table", I can find out which transactions come from an account which is valid.
I've tried linking them with
let transactions = LinkingObjects(fromType: Transaction.self, property: "fromAccount")
in the Account object and doing the inverse in the Transaction object. The best result I get is either an empty list or a null record.
I suppose the next question is, is there a way to do what I'm trying? I've also looked into subqueries but haven't had any luck with them (the documentation is super slim it seems for subqueries).
What I've done in the past is whenever a new transaction is created, it goes and fetches the full account object (using accountId) and stores it in that record but I feel there must be a better way. Surely.
There are a number of solutions but your linkingObject is a good option. It's really going to come down to what kind of queries you want to run.
So, let's start with a super simple example that will allow you to query transactions for any that have a parent account where valid is 'true' - that addresses your question.
class Account: Object {
#objc dynamic var id: String?
#objc dynamic var name: String?
#objc dynamic var valid: String?
}
class Transaction: Object {
#objc dynamic var id: String?
#objc dynamic var desc: String?
#objc dynamic var accountId: String?
#objc dynamic var parent_account: Account?
}
then create a couple of objects
let a0 = Account()
a0.name = "account 0"
a0.valid = "true"
let a1 = Account()
a1.name = "account 1"
a1.valid = "false"
let t0 = Transaction()
t0.desc = "trans 0"
let t1 = Transaction()
t1.desc = "trans 1"
t0.parent_account = a0
t1.parent_account = a1
try! realm.write {
realm.add([t0, t1])
}
once that data is written, if you want transactions where the parent_account's valid property == 'true'
let results = realm.objects(Transaction.self).filter("parent_account.valid == 'true'")
for account in results {
print(account.desc)
}
and the output is
Optional("trans 0")
Keep in mind this is very very basic and probably not going to work for your use case long term. Investigating LinkingObjects and inverse relationships will probably be a better solution but this should get you going.
Oh... probably making the active property a bool is going to be better than string.
Related
I am new to realm and iOS development so I apologize in advance if something isn’t explained properly or is just incorrect.
I have 2 Realm Object classes:
class Category: Object {
#objc dynamic var name: String = ""
#objc dynamic var color: String = ""
let trackers = List<Tracker>()
}
and
class Tracker: Object {
#objc dynamic var timeSegment: Int = 0
var parentCategory = LinkingObjects(fromType: Category.self, property:
"trackers")
}
I’m able to store new timeSegment properties consistently; however, the issue is that I cannot retrieve & display a collection of timeSegment values relating to their parentCategory. setting
var entries : Results<Tracker>?
produces all results for every category, which is the only result i'm able to pull so far after testing.
Any help is appreciated, and can follow up with any additional details. Thanks
You need to call objects on your Realm object with a filter for fetching only results that match a predicate. The realm object in this code is an instance of the Realm class.
func getTrackersWithName(_ name: String) -> Results<Tracker> {
return realm.objects(Tracker.self).filter("name = \"\(name)\"")
}
This tells Realm to fetch all objects that match the filter predicate. In this case, the filter predicate matches any object where the value of the "name" property matches the string that is passed into the method.
I've got a number of user properties in a user viewcontroller class ie
//user vars
var email: String?
var givenName: String?
var familyName:String?
var phone: String?
var dob: NSDate?
In a method within that class i retrieve user data from coredata and set the user text fields with that data in a loop
for i in 0 ..< userTextFields.count {
let field = userTextFields[i]
let fieldName = userTextFieldKeyNames[i]
let fieldText = currentUser.valueForKey(fieldName) as? String
field.text = fieldText
}
the fieldName variable in the loop matches the class's ivars above. Is there a way i can reference the ivars within the loop by matching it with the fieldName string so I can set the values of the ivars with the fetched coredata values ie in a literal sense saying something like the following ...
if self.property.name.text == fieldName {
self.property.value == fieldText
}
ie somehow resolving the various property names withing the class ... or is this bad design? .... if so any suggestions on achieving the same result in a better way
Not Swift-ish, as it's bypassing compile time type checking. Best option is to keep them all in a dictionary, and use a protocol to define allowed data types in the dictionary, but even that is rather poor
I'm new to iOS development and currently using Realm as database. My first tableview display Restaurant object and second table display customer objects. How can i link this two objects?. Means when i click each restaurant it will display different customer.
class Restaurant: Object {
dynamic var restname: String = ""
dynamic var date: String = ""
}
class Customer: Object {
dynamic var id = 0
dynamic var name: String = ""
dynamic var price: Float = 0.0
dynamic var drinks: Float = 0.0
override static func primaryKey() -> String? {
return "id"
}
}
You make references to your models like so
class Customer: Object {
dynamic var restaurant: Restaurant?
}
You also have the possibility to get reverse relationship with LinkingObjects(fromType:, property:)
You can write in your other model
class Restaurant: Object {
let customers = LinkingObjects(fromType: Customer.self, property: "restaurant")
}
That way you don't duplicate relationships.
If I understand, in Restaurant class put this:
dynamic var _customer = Optional(Customer())
or in Customer class put this line:
dynamic var _restaurant = Optional(Restaurant())
NOTE: Name of variable with lower dash, may be any name, my habit is to put lower dash
Hello I need to know what would be the standard way to implement this kind a functionality.I'll explain first the whole scenario
I have two Model classes User and Trips
class User: NSObject {
var email: String?
var password: String?
var firstName: String?
var lastName: String?
}
class Trip: NSObject {
var tripTitle: String?
var tripSummary: String?
var departureCountry: String?
var destinationCountry: String?
}
Now in the database I use join query in trips and User table when I fetch results in Trips Controller because I have to get the user information as well like his name
My Program is like this I get each variables from the backend and set them in trip Class object and then pass this object through segue. Now the problem here comes when I have to set the userinformation as well which I get in the same array. I know I have to create user object if I have to set these variables as well but how can I pass two objects through segue or should I have to to do some changing in the trips Model Class?
Is there any standard or proper way to handle this kind a situation ?
You can declare the object of User class inside the Trip class.
class Trip : NSObject
{
var userInfo : User?
var tripTitle : String?
var tripSummary : String?
var departureCountry : String?
var destinationCountry : String?
}
Then you can set the data like:
let trip = Trip() // Initialise trip
trip.userInfo = User() // Initialise user
trip.userInfo!.firstName = "Midhun"
trip.userInfo!.lastName = "MP"
I want to use Realm to my iOS app but I have a problem with the relationship. What I want to achieve is a relationship between the following two RLMobjects :
class Catalogue: RLMObject {
dynamic var ID = ""
dynamic var greekName = ""
dynamic var deutschName = ""
dynamic var createdAt = NSDate()
dynamic var updatedAt = NSDate()
override class func primaryKey() -> String? {
return "ID"
}
}
class Products: RLMObject {
dynamic var foodName = ""
dynamic var foodDescription = ""
dynamic var foodPrice = ""
dynamic var createdAt = NSDate()
dynamic var updatedAt = NSDate()
dynamic var category: Catalogue?
}
I am retrieving all my data from a server in JSON format and the problem is that
I can not set the category as relationship to Catalogue ID.
In my database the category field is a foreign key to the Catalogue ID.
Does anyone knows how can I do that in Realm?
Thank you in advance.
Rather than storing the Catalogue ID in the dynamic var category: Catalogue? relationship field you will need to find the Catalogue object and just store that directly. This is how you link objects and is an important and powerful part of using NoSQL type DB's like Realm.
I would also add an array of products relationship on Catalogue so that you can link all the products to the Catalogue itself.
You can see more discussion about this here if that wasn't fully clear. Hope this helps