dshakcsq64956 2017-09-10 01:28
浏览 84
已采纳

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

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.
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 js调用html页面需要隐藏某个按钮
  • ¥15 ads仿真结果在圆图上是怎么读数的
  • ¥20 Cotex M3的调试和程序执行方式是什么样的?
  • ¥20 java项目连接sqlserver时报ssl相关错误
  • ¥15 一道python难题3
  • ¥15 牛顿斯科特系数表表示
  • ¥15 arduino 步进电机
  • ¥20 程序进入HardFault_Handler
  • ¥15 oracle集群安装出bug
  • ¥15 关于#python#的问题:自动化测试