Skip to content

Commit abf0695

Browse files
committed
Add relation getters on base model structs
This prevents having to check the pointer before accessing a relation. It was already safe to access a nil R's Get() method, but this removes some of the extra typing and nil checks as a convenience. Previously: ```go var office *models.Office if employee != nil { office = employee.R.GetOffice() } ``` With this helper: ```go office := employee.GetOffice() ```
1 parent 2921b87 commit abf0695

File tree

1 file changed

+33
-6
lines changed

1 file changed

+33
-6
lines changed

templates/main/00_struct.go.tpl

+33-6
Original file line numberDiff line numberDiff line change
@@ -197,35 +197,62 @@ func (*{{$alias.DownSingular}}R) NewStruct() *{{$alias.DownSingular}}R {
197197
{{range .Table.FKeys -}}
198198
{{- $ftable := $.Aliases.Table .ForeignTable -}}
199199
{{- $relAlias := $alias.Relationship .Name -}}
200+
func (o *{{$alias.UpSingular}}) Get{{$relAlias.Foreign}}() *{{$ftable.UpSingular}} {
201+
if (o == nil) {
202+
return nil
203+
}
204+
205+
return o.R.Get{{$relAlias.Foreign}}()
206+
}
207+
200208
func (r *{{$alias.DownSingular}}R) Get{{$relAlias.Foreign}}() *{{$ftable.UpSingular}} {
201209
if (r == nil) {
202-
return nil
210+
return nil
203211
}
204-
return r.{{$relAlias.Foreign}}
212+
213+
return r.{{$relAlias.Foreign}}
205214
}
206215
207216
{{end -}}
208217
209218
{{- range .Table.ToOneRelationships -}}
210219
{{- $ftable := $.Aliases.Table .ForeignTable -}}
211220
{{- $relAlias := $ftable.Relationship .Name -}}
221+
func (o *{{$alias.UpSingular}}) Get{{$relAlias.Local}}() *{{$ftable.UpSingular}} {
222+
if (o == nil) {
223+
return nil
224+
}
225+
226+
return o.R.Get{{$relAlias.Local}}()
227+
}
228+
212229
func (r *{{$alias.DownSingular}}R) Get{{$relAlias.Local}}() *{{$ftable.UpSingular}} {
213230
if (r == nil) {
214-
return nil
231+
return nil
215232
}
216-
return r.{{$relAlias.Local}}
233+
234+
return r.{{$relAlias.Local}}
217235
}
218236
219237
{{end -}}
220238
221239
{{- range .Table.ToManyRelationships -}}
222240
{{- $ftable := $.Aliases.Table .ForeignTable -}}
223241
{{- $relAlias := $.Aliases.ManyRelationship .ForeignTable .Name .JoinTable .JoinLocalFKeyName -}}
242+
func (o *{{$alias.UpSingular}}) Get{{$relAlias.Local}}() {{printf "%sSlice" $ftable.UpSingular}} {
243+
if (o == nil) {
244+
return nil
245+
}
246+
247+
return o.R.Get{{$relAlias.Local}}()
248+
}
249+
224250
func (r *{{$alias.DownSingular}}R) Get{{$relAlias.Local}}() {{printf "%sSlice" $ftable.UpSingular}} {
225251
if (r == nil) {
226-
return nil
252+
return nil
227253
}
228-
return r.{{$relAlias.Local}}
254+
255+
return r.{{$relAlias.Local}}
229256
}
230257
231258
{{end -}}

0 commit comments

Comments
 (0)