GORM Playground Link
https://github.com/go-gorm/playground/pull/768
Description
I have a column in the database named NAME and in the struct I want to call it myName, so I have this struct:
type Organisation2 struct {
ID string `gorm:"primaryKey"`
myName string `gorm:"column:NAME"` // <<<< THIS SHOULD WORK, BUT ISN'T
}
func (Organisation2) TableName() string {
return "T_ORGANISATION"
}
but when I read a row, the struct attribute myName is never filled
I added a new test to the playground here
it fails with this output:
$ GORM_DIALECT=mysql go test
2024/10/23 00:10:27 testing mysql...
2024/10/23 00:10:28 /tmp/gorm-playground/main_test.go:14
[13.777ms] [rows:1] INSERT INTO `users` (`created_at`,`updated_at`,`deleted_at`,`name`,`age`,`birthday`,`company_id`,`manager_id`,`active`) VALUES ('2024-10-23 00:10:28.586','2024-10-23 00:10:28.586',NULL,'jinzhu',0,NULL,NULL,NULL,false)
2024/10/23 00:10:28 /tmp/gorm-playground/main_test.go:17
[1.880ms] [rows:1] SELECT * FROM `users` WHERE `users`.`id` = 1 AND `users`.`deleted_at` IS NULL ORDER BY `users`.`id` LIMIT 1
2024/10/23 00:10:28 /tmp/gorm-playground/my_test.go:20
[7.526ms] [rows:0] CREATE TABLE IF NOT EXISTS T_ORGANISATION (ID VARCHAR(36) NOT NULL, NAME VARCHAR(100) NOT NULL, PRIMARY KEY (ID) )
created table
2024/10/23 00:10:28 /tmp/gorm-playground/my_test.go:22
[12.384ms] [rows:1] DELETE FROM T_ORGANISATION
deleted all organisations
2024/10/23 00:10:28 /tmp/gorm-playground/my_test.go:24
[11.035ms] [rows:1] INSERT INTO T_ORGANISATION (ID, NAME) VALUES ('A', 'NAME')
inserted one organisation
2024/10/23 00:10:28 /tmp/gorm-playground/my_test.go:28
[1.797ms] [rows:1] SELECT * FROM `T_ORGANISATION` ORDER BY `T_ORGANISATION`.`id` LIMIT 1
--- FAIL: TestNameLikeOtherTests (0.03s)
my_test.go:33: Expected non-empty, got '""'
FAIL
exit status 1
FAIL gorm.io/playground 1.334s
(please note that I updated gen.go in my pull request due to https://github.com/go-gorm/playground/issues/751 - this is not relevant for the problem I am reporting here)
Comment From: maxant
I debugged gorm and found that only exported struct fields get mapped, so after renaming the field to Name instead of name, it works.
If I search for export in the docs, I cannot find anything that says fields must be exported in order to be mapped.
That link almost implies that it isn't necessary to make them exported:
Exported fields have all permissions when doing CRUD with GORM, and GORM allows you to change the field-level permission with tag, so you can make a field to be read-only, write-only, create-only, update-only or ignored
Could we add something to the docs to make it really clear that the fields need to be exported?
Comment From: maxant
created a PR for the docs: https://github.com/go-gorm/gorm.io/pull/797
Comment From: maxant
not really a bug -> closing