GORM Playground Link
https://github.com/go-gorm/playground/pull/431
Description
When using a scope that defines a subquery, Gorm generates invalid SQL that fails to execute. For example, in the provided playground, the generated SQL misses a table name and has unbalanced parentheses:
SELECT * FROM (SELECT * FROM () AS sub WHEREsub.deleted_atIS NULL
This does no happen when the scope avoids using its provided *gorm.DB to define the model to work with, and instead uses a global *gorm.DB.
Investigation
While digging into the issue, I found that the *gorm.DB that the scope returns has a Statement.TableExpr *clause.Expr which Vars []interface{} contains another *gorm.DB. That *gorm.DB itself has a Statement.TableExpr that points to the same clause.Expr.
This looks like an abnormal circular reference, which Gorm seems to handle by generating incomplete SQL rather than an infinite loop.
Comment From: li-jin-gou
please refer to this document https://gorm.cn/docs/method_chaining.html @ortolot