bun icon indicating copy to clipboard operation
bun copied to clipboard

Dynamic change relation table name

Open mantoze opened this issue 1 year ago • 0 comments

My structs:

type Client struct { bun.BaseModel bun:"table:clients,alias:c" ID int json:"id" bun:"id,pk,autoincrement" Title string json:"title" bun:"title" validate:"required,max=100" Code string json:"code" bun:"code" validate:"required" VatCode string json:"vat_code" bun:"vat_code" Address string json:"address" bun:"address" Email string json:"email" bun:"email" validate:"required,email" Phone string json:"phone" bun:"phone" }

type ProjectList struct { bun.BaseModel bun:"table:projects,alias:p" ID int json:"id" bun:"id,pk,autoincrement" ClientID int json:"client_id,omitempty" bun:"client_id" validate:"required,numeric" Client Client json:"client,omitempty" bun:"rel:has-one,join:client_id=id" Title string json:"title" bun:"title" validate:"required,max=200" Address string json:"address" bun:"address" validate:"required,max=250" }

Clients table name is dynamic: a_clients, b_clients,... with same structure. I try this select (but return error):

projects := []ProjectList{}
err := config.Db.
	NewSelect().
	Model(&projects).
	Relation("Client", func(q *bun.SelectQuery) *bun.SelectQuery {
		return q.ModelTableExpr("? as c", bun.Ident(slug+"_clients"))
	}).
	ModelTableExpr("? as p", bun.Ident(slug+"_projects")).
Scan(ctx)

How change Relation table name dynamically?

mantoze avatar Aug 15 '23 10:08 mantoze