登录
首页 >  Golang >  Go问答

如何在gorm中查询many-to-many关联表对象

来源:stackoverflow

时间:2024-02-24 23:45:24 186浏览 收藏

有志者,事竟成!如果你在学习Golang,那么本文《如何在gorm中查询many-to-many关联表对象》,就很适合你!文章讲解的知识点主要包括,若是你对本文感兴趣,或者是想搞懂其中某个知识点,就请你继续往下看吧~

问题内容

我在追随者的用户结构中有自引用的多对多表。其中 user_id 和 follower_id 是外键。

type user struct {
  id uint `gorm:"primary_key"`
  name        string     `gorm:"size:20"`
  lastname    string     `gorm:"size:40"`
  follow []user `gorm:"many2many:follow;association_jointable_foreignkey:follower_id"`
}

还有 followuser 函数,可以从身份验证令牌中获取用户 id,并从请求中获取其他用户 id。并且它需要检查用户是否尚未关注所选用户。我怎样才能做到这一点呢? 这是我尝试过的方法。

var CheckUser User
db.Preload("Follow", "user_id = ? AND follower_id = ?", selectedUser.ID, user.ID).Find(&CheckUser)
if CheckUser.ID != 0 {
    w.WriteHeader(http.StatusAlreadyReported)
    JSONResponse(struct{}{}, w)
    return
}

//Add user to followings
db.Model(&selectedUser).Association("Follow").Append(&user)
db.Model(&selectedUser).Updates(User{Followers: selectedUser.Followers + 1})
db.Model(&user).Updates(User{Following: user.Following + 1})

w.WriteHeader(http.StatusOK)

在此预加载语句之后,我收到表中的所有对象。用户 id = ?和 follower_id =?不起作用。 附:我使用 mariadb


解决方案


也许不是最好的解决方案,但这对我有帮助:

db.Raw("select * from users where id = (Select user_id from Follow where follower_id = ? and user_id = ? LIMIT 1) LIMIT 1", usrID, selectedUser.ID).Scan(&CheckUser)

以上就是《如何在gorm中查询many-to-many关联表对象》的详细内容,更多关于的资料请关注golang学习网公众号!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>