Table name when preloading in gorm

Asked 1 years ago, Updated 1 years ago, 61 views

db.Preload("Orders").Preload("Profile").Preload("Role").Find(&users)
//// SELECT* FROM users;
//// SELECT* FROM orders WHERE user_id IN (1, 2, 3, 4); // has many
//// SELECT* FROM profiles WHERE user_id IN (1,2,3,4); // has one
//// SELECT* FROM roles WHERE id IN (4,5,6); // belongs to

When you use Preload in gorm, even if you specify a table name in singular form, as in the example above, SQL is plural.(Profile->profiles)
Is there a way to specify the table name in singular form?

go gorm

2022-09-30 19:26

1 Answers

By default, GORM always chooses plural form as the table name.If there is no strong reason, it will be less troublesome to follow this custom.

If you really want to change this behavior, you must define the Tabler interface.

func(Profile)TableName()string{
  return "profile"
}

documentation:


2022-09-30 19:26

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.