A Go (golang) package that enhances the standard database/sql package by providing powerful data retrieval methods as well as DB-agnostic query building capabilities.
MIT License
636
stars
91
forks
source link
Fields in embedded struct should always be shadowed by fields in outer struct #37
type Foo struct {
ID int
Name string
Position int
}
But when inserting it into the database, you want to use a subquery for Position.
You can do this:
wrapper := struct{
Foo
Position dbx.Expression
}{
Foo: foo,
Position: dbx.NewExp("(SELECT COALESCE(MAX(f.position), 0)+1 AS position FROM foo )").
}
return db.Model(&wrapper).Insert()
Position has to be after Foo in the struct's definition for this to work.
The outer Position should shadow the embedded Foo's Position regardless of the order of the fields.
(Foo probably has to have a TableName method for this to work, the anonymous struct will inherit it).
Let's say you have a struct like this:
But when inserting it into the database, you want to use a subquery for Position. You can do this:
Position
has to be afterFoo
in the struct's definition for this to work. The outerPosition
should shadow the embeddedFoo
'sPosition
regardless of the order of the fields.(Foo probably has to have a
TableName
method for this to work, the anonymous struct will inherit it).