Optimize get childrens from token only

My tables have : User , Token and Pets…
a User have alot Pets.
a User have only 1 token, Token and Pet is FK with User via ID

My logic is want if user sent token string to server and i’ll get all pet of user.
so My code is
image

and result is working for me

image

But im newbie at backend, I want to know if there is another way to handle this problem

1.Token table is :
final class Token: Codable {
var id: Int?
var token: String
var userID: User.ID // FK

}
extension Token {
var user: Parent<Token, User> {
return parent(\Token.userID)
}
}
1.User table is :
final class User: Codable {
var id: Int?

}
extension User {
var pets: Children<User, Pet> {
return children(.userID)
}
}

3.Pet table is :

final class Pet: Codable {
var id: Int?
var name: String
var userID: User.ID
init(name: String, userID: User.ID) {
self.name = name
self.userID = userID
}
}
extension Pet {
var user: Parent<Pet, User> {
return parent(\Pet.userID)
}
}

@0xtim Can you please help with this when you get a chance? Thank you - much appreciated! :]

@choioi what you’re hitting there is the N+1 problem, which is a really difficult problem to solve. One way to do it is with this gist. Hopefully native Fluent support will come in the future

1 Like

I want to confirm some @0xtim :

  1. In my case, are you sure is N+1 , because I only get the pet list from a specified user, not all users.?, and in my model user. my petsis Computed Properties only. not var pets = [Pet]
    image

  2. what differrent from method 1 and method 2, same both of them same performance, i tested with 10k row pets for 2 user, and want get list of user 1 , my log is showing about 60ms for the 1st, and about 18ms for the second.

I thought that when using a foreign key, there would be advantages when accessing it rather than filter-based access

image

@0xtim Do you have any feedback about this? Thank you - much appreciated! :]

Hi @choioi

If your requirement is to use the token as a parameter in the request instead of the user as a URL parameter, then I would probably use an in-memory cache to store the token/user-id key-value pair when the user logs in.

1 Like

Thanks for your suggestion, I will try the cache to see the results @michaeltansg