1

I am trying to define a foreign key field in a Beego ORM model, but the application crashes during RunSyncdb with the following panic:

panic: runtime error: invalid memory address or nil pointer dereference
goroutine 1 \[running\]:
github.com/beego/beego/v2/client/orm.getColumnTyp
github.com/beego/beego/v2/client/orm.(\*modelCache).getDbCreateSQL
github.com/beego/beego/v2/client/orm.(\*commandSyncDb).Run
github.com/beego/beego/v2/client/orm.RunSyncdb
github.com/beego/beego/v2/adapter/orm.RunSyncdb

If I comment out the foreign key field:

Category *Category `orm:"rel(fk);null"

the program runs normally, so the crash only happens when the foreign key is present.

Model code

import (
    "time"
    "github.com/beego/beego/v2/client/orm"
)

type Category struct {
    Id      int        `orm:"column(id);auto"`
    Name    string     `orm:"column(name);size(128)"`
    Article []*Article `orm:"reverse(many)"`
}

type Tag struct {
    Id      int        `orm:"auto"`
    Name    string     `orm:"size(50)"`
    Article []*Article `orm:"reverse(many)"`
}

type Article struct {
    Id         int        `orm:"column(id);auto"`
    Title      string     `orm:"column(title);size(255)"`
    Abstract   string     `orm:"column(abstract);size(255);null"`
    Content    string     `orm:"column(content);type(longtext)"`
    Author     string     `orm:"column(author);size(100)"`
    Category   *Category  `orm:"rel(fk);null"`   // <-- foreign key
    Tags       []*Tag     `orm:"rel(m2m)"`
    CreateTime time.Time  `orm:"auto_now_add;type(datetime)"`
}

func init() {
    orm.RegisterModel(
        new(Category),
        new(Tag),
        new(Article),
    )
}

Environment

Go 1.25.1 Beego ORM v2.1.0 MySQL 8.0 Windows 10

How do I correctly define a foreign key (rel(fk)) in Beego ORM without causing this panic?

3
  • Out of curiosity: did you try orm:"null;rel(fk)" instead of orm:"rel(fk);null" ? Or even orm:"rel(fk)"? Commented Nov 10 at 6:56
  • Thanks for the suggestion! Yes, I tried orm:"null;rel(fk)" as well as just orm:"rel(fk)", but the result was the same. Commented Nov 13 at 7:23
  • Hmm. In PostgreSQL your code works just fine. Could you try in PG as well? Did you set force parameter to true or false in RunSyncdb ? Commented Nov 13 at 21:15

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.