英文:
Gorm field level permission is not working
问题
我正在使用gorm和postgresql,并尝试在表中创建一行新记录。这是我的postgresql表列。
id字段是主键,postgresql使用序列生成字段值。我想在只读权限下创建这个表的新记录,因为我不想在代码中设置它。
当我像下面这样做时,我可以从数据库中读取,但是gorm也想设置该字段,导致postgresql抛出异常。
type User struct {
    Id              int        `gorm:"column:id"`
    UUID            string     `gorm:"column:uuid"`
    FirstName       string     `gorm:"column:firstname"`
    MidName         string     `gorm:"column:midname"`
    LastName        string     `gorm:"column:lastname"`
}
当我像下面这样使用字段级别的权限时,在创建时它可以工作,因为gorm不会像预期的那样设置该字段。但是这次读取不起作用。
type User struct {
    Id              int        `gorm:"-"`
    UUID            string     `gorm:"column:uuid"`
    FirstName       string     `gorm:"column:firstname"`
    MidName         string     `gorm:"column:midname"`
    LastName        string     `gorm:"column:lastname"`
}
我尝试过gorm:"<-:false",gorm:"->"和gorm:"->;<-:read",但都失败了。
还尝试了在这个帖子中使用omit postgres.DB.Model(models.User{}).Omit("id").Create(newUser),但仍然不起作用。
我该如何实现这个?有什么想法吗?
提前感谢。
英文:
I'm using gorm with postgresql and trying to create a new row on a table. Here is my postgresql table columns.
id field is primary key and postgresql gives field values with a sequence.I'm trying to create a new record on this table with read permissions only because I don't want to set this on code.
When I do this like following, I can read from database but also gorm wants to set the field and postgresql throwing exeption.
type User struct {
	Id              int        `gorm:"column:id"`
	UUID            string     `gorm:"column:uuid"`
	FirstName       string     `gorm:"column:firstname"`
	MidName         string     `gorm:"column:midname"`
	LastName        string     `gorm:"column:lastname"`
}
When I use field level permission like this, it's working on create because gorm doesn't want to set this field like expected. But this time reads aren't working.
type User struct {
	Id              int        `gorm:"-"`
	UUID            string     `gorm:"column:uuid"`
	FirstName       string     `gorm:"column:firstname"`
	MidName         string     `gorm:"column:midname"`
	LastName        string     `gorm:"column:lastname"`
}
I've tried gorm:"<-:false" gorm:"->" and gorm:"->;<-:read" but fails.
Also tried omit with this post postgres.DB.Model(models.User{}).Omit("id").Create(newUser) but still not working.
How can I achieve this? Any idea?
Thanks in advance.
答案1
得分: 1
不是最好的选择,但通过添加钩子解决了这个问题。现在它可以按预期进行读取和写入,但仍在考虑字段级权限。
func (u *User) BeforeCreate(tx *gorm.DB) error {
    tx.Omit("id")
    return nil
}
英文:
Not the best choice but solved this issue with adding hook. Now it works as expected both read an write but still thinking about field level permissions.
func (u *User) BeforeCreate(tx *gorm.DB) error {
	tx.Omit("id")
	return nil
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。



评论