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
and result is working for me
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)
}
}
@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
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]
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
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.