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

想请问下关于gorm多对多关系的问题 #7

Closed
lfcleo opened this issue Oct 18, 2019 · 1 comment
Closed

想请问下关于gorm多对多关系的问题 #7

lfcleo opened this issue Oct 18, 2019 · 1 comment

Comments

@lfcleo
Copy link

lfcleo commented Oct 18, 2019

使用gorm 自引用多对多关系,如何反向查询呢?
比如:用户互相关注的表

Followers     []*User        `gorm:"many2many:follower;association_jointable_foreignkey:follow_id"` //用户关注表,自引用多对多关系。

查询用户的关注列表好做,如何查询关注用户(也就是用户的粉丝)列表?

@bonfy
Copy link
Owner

bonfy commented Nov 1, 2019

// FollowingIDs func
func (u *User) FollowingIDs() []int {
	var ids []int
	rows, err := db.Table("follower").Where("follower_id = ?", u.ID).Select("user_id, follower_id").Rows()
	if err != nil {
		log.Println("Counting Following error:", err)
		return ids
	}
	defer rows.Close()
	for rows.Next() {
		var id, followerID int
		rows.Scan(&id, &followerID)
		ids = append(ids, id)
	}
	return ids
}

将这个函数改改, .Where("follower_id = ?", u.ID) 改成 user_id = ? 试试,取出来的 follower_id 应该都是粉丝

@bonfy bonfy closed this as completed Jun 28, 2020
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants