dshakcsq64956
2017-09-10 01:28
浏览 79

未通过一对多关联创建外键

I have a Task type that has a list of Runner type objects in it. I am trying to map it to database using golang gorm but it doesn't have foreign key and i am getting invalid association during migration

My Task struct:

type Task struct {
    gorm.Model
    Name        string `gorm:"not null;unique_index"`
    Description string
    Runners     []Runner
}

My Runner struct:

type Runner struct {
    gorm.Model
    Name        string `gorm:"not null;unique"`
    Description string
}

My migration code:

func migrateSchema () (err error) {
    db, err := context.DBProvider()

    if err != nil {
        return
    }

    db.Model(&Task{}).Related(&Runner{})
    db.AutoMigrate(&Task{})
    db.AutoMigrate(&Runner{})

    return
}

On db.AutoMigrate(&Task{}) I get invalid association message in console and when I check the database there is no foreign key created or no reference field created on runners table

What am I doing wrong?

  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • duangongqiong6958 2017-09-10 12:14
    已采纳

    I had a similar issue, and it took me forever to figure it out. I believe the GORM documentation could definitely be better. Here's the relevant code snippet from the GORM site:

    //User has many emails, UserID is the foreign key
    type User struct {
        gorm.Model
        Emails   []Email
    }
    
    type Email struct {
        gorm.Model
        Email   string
        UserID  uint
    }
    
    db.Model(&user).Related(&emails)
    //// SELECT * FROM emails WHERE user_id = 111; // 111 is user's primary key
    

    Why your code isn't working:

    1. First you need to add a TaskID field to your Runner struct.
    2. db.Model(&Task{}).Related(&Runner{}) doesn't do what you think it does. If you look at the code snippet from GORM, the SELECT comment kind of explains it (not very well though). The example is assuming that the &user is already populated and has an ID of 111, then it fetches the emails storing them in &emails that match the UserID of &user.
    打赏 评论

相关推荐 更多相似问题