I have a Room search, which requires the Room struct to contain the entire User struct.
type Room struct {
ID *int64 `json:"id"`
CreatedAt *time.Time `json:"created_at,omitempty" gorm:"not null"`
UpdatedAt *time.Time `json:"updated_at,omitempty"`
DeletedAt *time.Time `json:"deleted_at,omitempty"`
User *User `json:"user,omitempty"`
UserID *int64 `json:"user_id,omitempty"`
}
and
type User struct {
ID *int64 `json:"id"`
CreatedAt *time.Time `json:"created_at,omitempty" gorm:"not null"`
UpdatedAt *time.Time `json:"updated_at,omitempty"`
DeletedAt *time.Time `json:"deleted_at,omitempty"`
FirstName *string `json:"first_name,omitempty"`
LastName *string `json:"last_name,omitempty"`
}
while the search function looks like this
func searchRoom(db *gorm.DB, q string) ([]Room, error) {
q = "%" + q + "%"
rooms := []Room{}
db.Preload("User").
Joins("LEFT JOIN users on rooms.user_id = users.id").
Where(
"CONCAT(users.first_name, ' ', users.last_name) LIKE ?",
q,
).
Find(&rooms)
return rooms, nil
}
This works pretty well the way it is expected, however, to me this looks a bit clunky, I went through Gorm docs, but didn't find anything else which could help me.
I could use the db.Raw
method, but that does not fill the user struct automatically.
Is there a better way to use Gorm and make it more performant?