Skip to content

Commit

Permalink
Add join assoc query builder (#298)
Browse files Browse the repository at this point in the history
  • Loading branch information
Fs02 committed Jun 26, 2022
1 parent 7edbcb0 commit 57e2c90
Show file tree
Hide file tree
Showing 2 changed files with 50 additions and 0 deletions.
27 changes: 27 additions & 0 deletions query.go
Expand Up @@ -182,6 +182,18 @@ func (q Query) Joinf(expr string, args ...interface{}) Query {
return q
}

// JoinAssoc current table with other table based on association field.
func (q Query) JoinAssoc(assoc string, filter ...FilterQuery) Query {
return q.JoinAssocWith("JOIN", assoc, filter...)
}

// JoinAssocWith current table with other table based on association field.
func (q Query) JoinAssocWith(mode string, assoc string, filter ...FilterQuery) Query {
NewJoinAssocWith(mode, assoc, filter...).Build(&q)

return q
}

// Where query.
func (q Query) Where(filters ...FilterQuery) Query {
q.WhereQuery = q.WhereQuery.And(filters...)
Expand Down Expand Up @@ -467,6 +479,21 @@ func JoinWith(mode string, table string, from string, to string, filter ...Filte
return query
}

// JoinAssoc create a query with chainable syntax, using join as the starting point.
func JoinAssoc(assoc string, filter ...FilterQuery) Query {
return JoinAssocWith("JOIN", assoc, filter...)
}

// JoinAssocWith create a query with chainable syntax, using join as the starting point.
func JoinAssocWith(mode string, assoc string, filter ...FilterQuery) Query {
query := newQuery()
query.JoinQuery = []JoinQuery{
NewJoinAssocWith(mode, assoc, filter...),
}
query.AddPopulator(&query.JoinQuery[0])
return query
}

// Joinf create a query with chainable syntax, using join as the starting point.
func Joinf(expr string, args ...interface{}) Query {
query := newQuery()
Expand Down
23 changes: 23 additions & 0 deletions query_test.go
Expand Up @@ -377,6 +377,29 @@ func TestQuery_Joinf(t *testing.T) {
shallowAssertQuery(t, result, rel.Joinf("JOIN transactions ON transacations.id=?", 1).From("users"))
}

func TestQuery_JoinAssoc(t *testing.T) {
result := rel.Query{
Table: "users",
JoinQuery: []rel.JoinQuery{
{
Mode: "JOIN",
Table: "transactions",
To: "transactions.user_id",
From: "users.id",
Assoc: "transactions",
},
},
CascadeQuery: true,
}

shallowAssertQuery(t, result,
rel.Build("", rel.From("users").JoinAssoc("transactions")).
Populate(rel.NewDocument(&rel.User{}, false).Meta()))
shallowAssertQuery(t, result,
rel.Build("users", rel.JoinAssoc("transactions")).
Populate(rel.NewDocument(&rel.User{}, false).Meta()))
}

func TestQuery_Where(t *testing.T) {
tests := []struct {
Case string
Expand Down

0 comments on commit 57e2c90

Please sign in to comment.