我正在处理复杂的结构数据库,更新后我们开始使用 GORM,所以我需要使用 GORM 转换这个脚本。
query := `
SELECT * FROM foo
UNION ALL
SELECT * FROM bar WHERE id=1`
rows, err := db.Query(query)
Run Code Online (Sandbox Code Playgroud)
最好的方法是什么?
Note that gorm doesn't support UNION directly, you need to use db.Raw to do UNIONs:
db.Raw("? UNION ?",
db.Select("*").Model(&Foo{}),
db.Select("*").Model(&Bar{}),
).Scan(&union)
Run Code Online (Sandbox Code Playgroud)
the above will produce something like the following:
SELECT * FROM "foos"
WHERE "foos"."deleted_at" IS NULL
UNION
SELECT * FROM "bars"
WHERE "bars"."deleted_at" IS NULL
Run Code Online (Sandbox Code Playgroud)