1

I am trying to create a rest API. I have already a database. I want to create a struct linked to a database table. But when I run the project beego automatically creates an "id" primary key for the model registered. How to avoid this in beego?

My code example:

Model:
type Person struct {
    PersonId string `json:"person_id"`
    name string `json:"name"`
    email string `json:"email"`
}

Problem: Encounter need a primary key field when using beego It creates an id field in db table with default null value.

Note: person_id is the primary key in person table.

3
  • What is the Database you are using? Some DBs automatically create primary keys, so your problem might be with the DB and not with beego. Commented Nov 29, 2021 at 22:22
  • I am using mysql database. It has already a primary key. I just created a model using those fields. Beego needs an Id in the struct and adds it on the database with default value 0. Commented Nov 30, 2021 at 2:44
  • Were you able to solve the problem? Commented Dec 1, 2021 at 12:07

1 Answer 1

1

If you want Beego’s ORM to have a different primary key, you should use this:


type Person struct {
    PersonId int64 `orm:"pk" json:"person_id"`
    name string `json:"name"`
    email string `json:"email"`
}

You can check the official documentation here in the primary key section: Beego Model Definition

This might be happening because when creating your table you have primary_key set to auto. Which is the default Beego behaviour.

Please check this article also: https://developpaper.com/question/beegos-orm-gives-the-primary-key-value-every-update-delete-read/

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.