From 57e2c90f6a68059a2fc9ee37c7f709b3e09e197d Mon Sep 17 00:00:00 2001 From: Surya Asriadie Date: Sun, 26 Jun 2022 13:19:05 +0900 Subject: [PATCH] Add join assoc query builder (#298) --- query.go | 27 +++++++++++++++++++++++++++ query_test.go | 23 +++++++++++++++++++++++ 2 files changed, 50 insertions(+) diff --git a/query.go b/query.go index 726bc40e..4de73fe2 100644 --- a/query.go +++ b/query.go @@ -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...) @@ -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() diff --git a/query_test.go b/query_test.go index af0d8376..3164780e 100644 --- a/query_test.go +++ b/query_test.go @@ -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