Skip to content

Commit

Permalink
add BelongsToAs function so it can be posible to assign an alias to o…
Browse files Browse the repository at this point in the history
…wner table
  • Loading branch information
larrymjordan committed Jan 19, 2018
1 parent eeb02e2 commit aa4a7eb
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 0 deletions.
15 changes: 15 additions & 0 deletions belongs_to.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,12 @@ func (c *Connection) BelongsTo(model interface{}) *Query {
return Q(c).BelongsTo(model)
}

// BelongsToAs adds a "where" clause based on the "ID" of the
// "model" passed into it using an alias.
func (c *Connection) BelongsToAs(model interface{}, as string) *Query {
return Q(c).BelongsToAs(model, as)
}

// BelongsTo adds a "where" clause based on the "ID" of the
// "model" passed into it.
func (q *Query) BelongsTo(model interface{}) *Query {
Expand All @@ -16,6 +22,15 @@ func (q *Query) BelongsTo(model interface{}) *Query {
return q
}

// BelongsToAs adds a "where" clause based on the "ID" of the
// "model" passed into it, using an alias.
func (q *Query) BelongsToAs(model interface{}, as string) *Query {
m := &Model{Value: model}
m.tableName = as
q.Where(fmt.Sprintf("%s = ?", m.associationName()), m.ID())
return q
}

// BelongsToThrough adds a "where" clause that connects the "bt" model
// through the associated "thru" model.
func (c *Connection) BelongsToThrough(bt, thru interface{}) *Query {
Expand Down
11 changes: 11 additions & 0 deletions belongs_to_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,17 @@ func Test_BelongsTo(t *testing.T) {
r.Equal(ts("SELECT enemies.A FROM enemies AS enemies WHERE user_id = ?"), sql)
}

func Test_BelongsToAs(t *testing.T) {
r := require.New(t)

q := PDB.BelongsToAs(&User{ID: 1}, "u")

m := &pop.Model{Value: &Enemy{}}

sql, _ := q.ToSQL(m)
r.Equal(ts("SELECT enemies.A FROM enemies AS enemies WHERE u_id = ?"), sql)
}

func Test_BelongsToThrough(t *testing.T) {
r := require.New(t)

Expand Down

0 comments on commit aa4a7eb

Please sign in to comment.