feat: support inner join

This commit is contained in:
a631807682 2022-08-06 23:30:56 +08:00
parent 6e03b97e26
commit e9c8c5bec4
No known key found for this signature in database
GPG Key ID: 137D1D75522168AB
4 changed files with 31 additions and 6 deletions

View File

@ -177,7 +177,7 @@ func BuildQuerySQL(db *gorm.DB) {
}
fromClause.Joins = append(fromClause.Joins, clause.Join{
Type: clause.LeftJoin,
Type: join.JoinType,
Table: clause.Table{Name: relation.FieldSchema.Table, Alias: tableAliasName},
ON: clause.Where{Exprs: exprs},
})

View File

@ -183,18 +183,26 @@ func (db *DB) Or(query interface{}, args ...interface{}) (tx *DB) {
// db.Joins("JOIN emails ON emails.user_id = users.id AND emails.email = ?", "jinzhu@example.org").Find(&user)
// db.Joins("Account", DB.Select("id").Where("user_id = users.id AND name = ?", "someName").Model(&Account{}))
func (db *DB) Joins(query string, args ...interface{}) (tx *DB) {
return joins(db, clause.LeftJoin, query, args...)
}
func (db *DB) InnerJoins(query string, args ...interface{}) (tx *DB) {
return joins(db, clause.InnerJoin, query, args...)
}
func joins(db *DB, joinType clause.JoinType, query string, args ...interface{}) (tx *DB) {
tx = db.getInstance()
if len(args) == 1 {
if db, ok := args[0].(*DB); ok {
if where, ok := db.Statement.Clauses["WHERE"].Expression.(clause.Where); ok {
tx.Statement.Joins = append(tx.Statement.Joins, join{Name: query, Conds: args, On: &where})
tx.Statement.Joins = append(tx.Statement.Joins, join{Name: query, Conds: args, On: &where, JoinType: joinType})
return
}
}
}
tx.Statement.Joins = append(tx.Statement.Joins, join{Name: query, Conds: args})
tx.Statement.Joins = append(tx.Statement.Joins, join{Name: query, Conds: args, JoinType: joinType})
return
}

View File

@ -49,9 +49,10 @@ type Statement struct {
}
type join struct {
Name string
Conds []interface{}
On *clause.Where
Name string
Conds []interface{}
On *clause.Where
JoinType clause.JoinType
}
// StatementModifier statement modifier interface

View File

@ -229,3 +229,19 @@ func TestJoinWithSoftDeleted(t *testing.T) {
t.Fatalf("joins NamedPet and Account should not empty:%v", user2)
}
}
func TestInnerJoins(t *testing.T) {
user := *GetUser("inner-joins-1", Config{Company: true, Manager: true, Account: true, NamedPet: false})
DB.Create(&user)
var user2 User
var err error
err = DB.InnerJoins("Company").InnerJoins("Manager").InnerJoins("Account").First(&user2, "users.name = ?", user.Name).Error
AssertEqual(t, err, nil)
CheckUser(t, user2, user)
// NamedPet is nil
err = DB.InnerJoins("NamedPet").InnerJoins("Company").InnerJoins("Manager").InnerJoins("Account").First(&user2, "users.name = ?", user.Name).Error
AssertEqual(t, err, gorm.ErrRecordNotFound)
}