Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add join assoc query builder #298

Merged
merged 1 commit into from Jun 26, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
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