GORM Playground Link

https://github.com/go-gorm/playground/pull/754

Description

I was under the impression that using a grouped where cond in a query scope, would apply to the query only 1 time.

The results I'm seeing from applying a grouped cond in a query scope such as:

func ScopeSomething(a,b string) func (*gorm.DB) *gorm.DB {
  return func (db *gorm.DB) *gorm.DB {
    return db.Where(
      // would anticipate the following being added to query as ("field_a" = ? OR "field_b" = ?)
      db.Where("field_a", a).Or("field_b", b),
    )
  }
}

This generates a query such as:

SELECT * FROM sometable WHERE field_a = ? or field_b = ? AND (field_a = ? OR field_b = ?)

The desired behavior can be achieved by doing the following but it doesn't feel as declarative.

func ScopeSomething(a,b string) func (*gorm.DB) *gorm.DB {
  return func (db *gorm.DB) *gorm.DB {
    return db.Where("field_a = ? OR field_b = ?", a, b)
  }
}

Comment From: OliverChao

Right. I have noticed this issue, too. Is there any pointers to fixing this bug?

Comment From: cbaker

Right. I have noticed this issue, too. Is there any pointers to fixing this bug?

Unfortunately, I haven't made the time to dig into it myself yet. It strikes me as odd that it actually does generate part of the query in the anticipated manner but also appends the redundant call. I suspect that both calls to db.Where are adding conditions independently somehow.

Comment From: a631807682

Use session to avoid repeated changes to the db instance https://gorm.io/docs/method_chaining.html#Reusability-and-Safety

Comment From: cbaker

Use session to avoid repeated changes to the db instance https://gorm.io/docs/method_chaining.html#Reusability-and-Safety

I don't believe this is applicable to the documentation you've linked since we aren't trying to re-use a gorm.DB and group conditions are explicitly listed in the documentation as a feature: https://gorm.io/docs/advanced_query.html#Group-Conditions

Please consider taking a second look.