| 374 | } |
| 375 | |
| 376 | func (c chainG[T]) Joins(jt clause.JoinTarget, on func(db JoinBuilder, joinTable clause.Table, curTable clause.Table) error) ChainInterface[T] { |
| 377 | return c.with(func(db *DB) *DB { |
| 378 | if jt.Table == "" { |
| 379 | jt.Table = clause.JoinTable(strings.Split(jt.Association, ".")...).Name |
| 380 | } |
| 381 | |
| 382 | q := joinBuilder{db: db.Session(&Session{NewDB: true, Initialized: true}).Table(jt.Table)} |
| 383 | if on != nil { |
| 384 | if err := on(&q, clause.Table{Name: jt.Table}, clause.Table{Name: clause.CurrentTable}); err != nil { |
| 385 | db.AddError(err) |
| 386 | } |
| 387 | } |
| 388 | |
| 389 | j := join{ |
| 390 | Name: jt.Association, |
| 391 | Alias: jt.Table, |
| 392 | Selects: q.db.Statement.Selects, |
| 393 | Omits: q.db.Statement.Omits, |
| 394 | JoinType: jt.Type, |
| 395 | } |
| 396 | |
| 397 | if where, ok := q.db.Statement.Clauses["WHERE"].Expression.(clause.Where); ok { |
| 398 | j.On = &where |
| 399 | } |
| 400 | |
| 401 | if jt.Subquery != nil { |
| 402 | joinType := j.JoinType |
| 403 | if joinType == "" { |
| 404 | joinType = clause.LeftJoin |
| 405 | } |
| 406 | |
| 407 | if db, ok := jt.Subquery.(interface{ getInstance() *DB }); ok { |
| 408 | stmt := db.getInstance().Statement |
| 409 | if len(j.Selects) == 0 { |
| 410 | j.Selects = stmt.Selects |
| 411 | } |
| 412 | if len(j.Omits) == 0 { |
| 413 | j.Omits = stmt.Omits |
| 414 | } |
| 415 | } |
| 416 | |
| 417 | expr := clause.NamedExpr{SQL: fmt.Sprintf("%s JOIN (?) AS ?", joinType), Vars: []interface{}{jt.Subquery, clause.Table{Name: j.Alias}}} |
| 418 | |
| 419 | if j.On != nil { |
| 420 | expr.SQL += " ON ?" |
| 421 | expr.Vars = append(expr.Vars, clause.AndConditions{Exprs: j.On.Exprs}) |
| 422 | } |
| 423 | |
| 424 | j.Expression = expr |
| 425 | } |
| 426 | |
| 427 | db.Statement.Joins = append(db.Statement.Joins, j) |
| 428 | sort.Slice(db.Statement.Joins, func(i, j int) bool { |
| 429 | return db.Statement.Joins[i].Name < db.Statement.Joins[j].Name |
| 430 | }) |
| 431 | return db |
| 432 | }) |
| 433 | } |