Skip to content

dynamic select without knowing the table name #691

Answered by jhhom
chekaiyin asked this question in Q&A
Discussion options

You must be logged in to vote

Hi @chekaiyin, if I understand correctly, you need a universal loadCodeTable that can be called on slices of any structs, not just Account struct.

The following is what I came up with, not sure if it solves your problem.

You can retrieve all records to the Account struct by simply passing a reference of the slice to the Scan function like so:

func loadCodeTable2(db *bun.DB, codeTable CodeTable) ([]Account, error) {
	accounts := make([]Account, 0)
	err := db.NewSelect().Model(codeTable).Scan(context.Background(), &accounts)
	return accounts, err
}

If you need the function to be universal across every type, not just for Account, you can use Golang generics.

func loadCodeTable[T any](db *bun.DB

Replies: 1 comment 1 reply

Comment options

You must be logged in to vote
1 reply
@chekaiyin
Comment options

Answer selected by chekaiyin
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
2 participants