Your Question

Hi, there I have following models accounts, class_members and classes.

Business logic if student (account has role student) want to join class. They need to send request and wait teacher to approve to join class. My question is how to edit status field in associate table for stamp request status like approved, requested, denied

Relationship

Screenshot 2565-08-02 at 00 27 11

  • account (role student) can join many class
  • class can own by account (role teacher)

This is Models

type Account struct {
    gorm.Model
    Title     string
    Fname     string `gorm:"column:fname"`
    Lname     string `gorm:"column:lname"`
    StudentNo string
    Email     string  `gorm:"unique"`
    Classes   []Class `gorm:"many2many:class_members"`
    School    School
    SchoolID  *uint
    Role      Role
    RoleID    uint
    Password  string
}
type Class struct {
    gorm.Model
    ClassName    string
    ClassType    string
    ExpireAt     time.Time
    ClassCode    string    `gorm:"size:6"`
    Participants []Account `gorm:"many2many:class_members"`
    Owner        Account
    OwnerID      uint
}
type ClassMember struct {
    Status    string
    AccountID uint `gorm:"primaryKey"`
    ClassID   uint `gorm:"primaryKey"`
    CreatedAt time.Time
    DeletedAt gorm.DeletedAt
}

The document you expected this should be explained

I have searched follow thees link but I still not sure how to edit the status field in associate table. I think it should explain in associations page

https://gorm.io/docs/many_to_many.html https://gorm.io/docs/associations.html

Expected answer

Cloud you give some solution to edit status field ?

Comment From: a631807682

https://gorm.io/docs/many_to_many.html#Customize-JoinTable

Comment From: wavemoroc001

@a631807682 Cloud you give some detail how to stamp status in class member table ?

Comment From: a631807682

This design means that status is neither account status nor class status, we can't read status from anywhere and populate it, I don't know if hook or callback are useful to you, if not you can only insert each table yourself

Comment From: alfman99

What is the way to pass a custom value you want for the custom field to the BeforeCreate hook, as it cannot receive parameters?

Comment From: wavemoroc001

@a631807682
Maybe it need to change relationship from many2many to one to many in go models is that right ? and mange table by myself

Comment From: a631807682

@alfman99 use settings or context https://gorm.io/docs/settings.html#content-inner

@wavemoroc001 If this can meet your needs, of course. in fact, our association operation is also implemented based on ordinary api, you can also implement it according to your own needs.

Comment From: alfman99

@alfman99 use settings or context https://gorm.io/docs/settings.html#content-inner

Yes, this solves my problem, do you know if this solution its thread safe?

Thanks!