added record.ExpandedOne(rel) and record.ExpandedAll(rel) helpers

This commit is contained in:
Gani Georgiev
2023-07-14 15:20:48 +03:00
parent 8e2246113a
commit 4962dc618b
4 changed files with 118 additions and 0 deletions

View File

@@ -378,6 +378,56 @@ func (m *Record) GetStringSlice(key string) []string {
return list.ToUniqueStringSlice(m.Get(key))
}
// ExpandedOne retrieves a single relation Record from the already
// loaded expand data of the current model.
//
// If the requested expand relation is multiple, this method returns
// only first available Record from the expanded relation.
//
// Returns nil if there is no such expand relation loaded.
func (m *Record) ExpandedOne(relField string) *Record {
if m.expand == nil {
return nil
}
rel := m.expand.Get(relField)
switch v := rel.(type) {
case *Record:
return v
case []*Record:
if len(v) > 0 {
return v[0]
}
}
return nil
}
// ExpandedAll retrieves a slice of relation Records from the already
// loaded expand data of the current model.
//
// If the requested expand relation is single, this method normalizes
// the return result and will wrap the single model as a slice.
//
// Returns nil slice if there is no such expand relation loaded.
func (m *Record) ExpandedAll(relField string) []*Record {
if m.expand == nil {
return nil
}
rel := m.expand.Get(relField)
switch v := rel.(type) {
case *Record:
return []*Record{v}
case []*Record:
return v
}
return nil
}
// Retrieves the "key" json field value and unmarshals it into "result".
//
// Example