go-pg/pg

Help me to get the relation.

velocent opened this issue · 0 comments

Discussed in #1977

Originally posted by Sirius198 March 23, 2023

type Friend struct {
	tableName struct{}  `pg: tbl_friends,alias:tf"`
	Id        uuid.UUID `pg:"id, type:uuid"`
	AccountId uuid.UUID `pg:"account_id,type:uuid"`
	FriendId  uuid.UUID `pg:"friend_id,type:uuid"`
	Profile   *Profile  `pg:"rel:has-one, fk:friend_id, join_fk:account_id"`
}

type Profile struct {
	tableName         struct{}  `pg:"tbl_profiles,alias:tp"`
	Id                uuid.UUID `pg:"id,type:uuid"`
	AccountId         uuid.UUID `pg:"account_id,type:uuid"`
	PlayerCode        string    `pg:"player_code"`
	PlayerName        string    `pg:"player_name"`
}

var friends []models.Friend
var accountID uuid.UUID
db.Model(&friends).Relation("Profile").Where("tf.account_id = ?", accountID).Select()

After executing this query, friends.Profile is always nil.

My query result is same with below SQL query?

SELECT * FROM tbl_friends tf LEFT JOIN tbl_profiles tp ON tf.friend_id = tp.account_id WHERE tf.account_id = '1111-1111-1111-'

Thanks.