Skip to content

"CASE WHEN" subquery as value in InsertQuery #861

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

You must be logged in to vote

This is one way I figured out how to do it using the InsertQuery and Value method:

func main() {
	// ...
	c := &Comment{
		ThreadID: 1,
		UserID:   1,
	}
	_, err := db.NewInsert().Model(c).
		Value("is_thread_author", `
	(CASE WHEN (SELECT user_id FROM threads WHERE id = ?) = ? THEN TRUE ELSE FALSE END)`, c.ThreadID, c.UserID).
		Exec(ctx)
	if err != nil {
		panic(fmt.Errorf("error, %w", err))
	}
}

type Comment struct {
	bun.BaseModel `bun:"table:comments"`

	ThreadID       int64 `bun:"thread_id"`
	UserID         int64 `bun:"user_id"`
	IsThreadAuthor bool  `bun:"is_thread_author"`
	// ... other columns omitted
}

It will generate an SQL query like this:

INSERT INTO "comments" ("thread_id", "

Replies: 1 comment 1 reply

Comment options

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

Answer selected by pof3
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