refactor(database): ♻️ simplify relation type handling
Some checks failed
Build , Vet Test, and Lint / Run Vet Tests (1.24.x) (push) Successful in -26m33s
Build , Vet Test, and Lint / Run Vet Tests (1.23.x) (push) Successful in -26m6s
Build , Vet Test, and Lint / Lint Code (push) Successful in -26m1s
Build , Vet Test, and Lint / Build (push) Successful in -26m14s
Tests / Integration Tests (push) Failing after -26m47s
Tests / Unit Tests (push) Successful in -26m35s

* Consolidate related type determination logic
* Improve clarity in slice creation for results
* Enhance foreign key field name handling
This commit is contained in:
Hein
2026-02-03 08:40:11 +02:00
parent 5269ae4de2
commit 50d0caabc2

View File

@@ -633,12 +633,7 @@ func checkIfRelationAlreadyLoaded(parents reflect.Value, relationName string) (r
// Check if it's a pointer (has-one/belongs-to) // Check if it's a pointer (has-one/belongs-to)
if !relationField.IsNil() { if !relationField.IsNil() {
// Already loaded! Collect all related records from all parents // Already loaded! Collect all related records from all parents
var relatedType reflect.Type relatedType := relationField.Type()
if relationField.Elem().IsValid() {
relatedType = relationField.Type()
} else {
relatedType = relationField.Type()
}
allRelated := reflect.MakeSlice(reflect.SliceOf(relatedType), 0, parents.Len()) allRelated := reflect.MakeSlice(reflect.SliceOf(relatedType), 0, parents.Len())
for j := 0; j < parents.Len(); j++ { for j := 0; j < parents.Len(); j++ {
p := parents.Index(j) p := parents.Index(j)
@@ -785,7 +780,7 @@ func (b *BunSelectQuery) loadRelationLevel(ctx context.Context, parentRecords re
} }
// Create a slice to hold the results // Create a slice to hold the results
resultsSlice := reflect.MakeSlice(reflect.SliceOf(reflect.PtrTo(relatedType)), 0, len(fkValues)) resultsSlice := reflect.MakeSlice(reflect.SliceOf(reflect.PointerTo(relatedType)), 0, len(fkValues))
resultsPtr := reflect.New(resultsSlice.Type()) resultsPtr := reflect.New(resultsSlice.Type())
resultsPtr.Elem().Set(resultsSlice) resultsPtr.Elem().Set(resultsSlice)
@@ -876,7 +871,7 @@ func extractForeignKeyValues(records reflect.Value, fkFieldName string) ([]inter
fkField := record.FieldByName(fkFieldName) fkField := record.FieldByName(fkFieldName)
if !fkField.IsValid() { if !fkField.IsValid() {
// Try capitalized version // Try capitalized version
fkField = record.FieldByName(strings.Title(fkFieldName)) fkField = record.FieldByName(strings.ToUpper(fkFieldName[:1]) + fkFieldName[1:])
} }
if !fkField.IsValid() { if !fkField.IsValid() {
// Try finding by json tag // Try finding by json tag