This repository has been archived on 2025-03-16. You can view files and clone it. You cannot open issues or pull requests or push a commit.
Files
boilerplate/internal/utils/search.go
2025-03-15 18:54:30 +07:00

30 lines
603 B
Go

package utils
import (
"app/internal/database"
"fmt"
"gorm.io/gorm/clause"
"reflect"
)
func FindPhraseByStringFields[T any](phrase string, entity T) ([]*T, error) {
db := database.GetInstance().Preload(clause.Associations)
structType := reflect.TypeOf(entity)
for i := 0; i < structType.NumField(); i++ {
field := structType.Field(i)
if field.Type.Kind() == reflect.Pointer {
field.Type = field.Type.Elem()
}
if field.Type.Kind() == reflect.String {
db.Where(fmt.Sprintf("`%s` like ?", field.Name), "%"+phrase+"%")
}
}
var items []*T
db.Find(&items)
return items, nil
}