英文:
GORM deleted_at" IS NULL
问题
我刚开始学习GORM,并且正在尝试从一对多的表中获取数据。
我有两个表:users和documents。一个用户可以拥有多个文档。当我尝试获取文档时,我一直收到以下错误信息:
documents: unsupported relations for schema User
SELECT * FROM "users" WHERE "users"."deleted_at" IS NULL
以下是我尝试获取数据的代码:
type User struct {
gorm.Model
Name string
Email string
Password string
Documents []Document
}
type Document struct {
gorm.Model
Name string
DateCreated string
UserID uint
}
获取数据的函数:
func GetAll(db *gorm.DB) ([]models.User, error) {
var users []models.User
// err := db.Model(&models.User{}).Preload("documents").Find(&users).Error
err:=db.Preload("documents").Find(&[]models.User{}).Error
fmt.Println(err)
fmt.Println("got users")
return users, err
}
我在这里做错了什么?
英文:
I just started learning GORM and currently trying to fetch data from one to many tables.
I have two tables :users and documents. A user can have multiple documents . When i try fetching documents I keep getting the error
documents: unsupported relations for schema User
SELECT * FROM "users" WHERE "users"."deleted_at" IS NULL
Below is the code where I attempt to fetch data
type User struct {
gorm.Model
Name string
Email string
Password string
Documents []Document
}
type Document struct {
gorm.Model
Name string
DateCreated string
UserID uint
}
Function to fetch data
func GetAll(db *gorm.DB) ([]models.User, error) {
var users []models.User
// err := db.Model(&models.User{}).Preload("documents").Find(&users).Error
err:=db.Preload("documents").Find(&[]models.User{}).Error
fmt.Println(err)
fmt.Println("got users")
return users, err
}
What am I doing wrong here?
答案1
得分: 2
这是因为您的表中不包含相关字段"deleted_at",而您使用了gorm.Model。
如果您使用了gorm.Model,它会自动集成4个字段:
ID:自增的整数主键
CreatedAt:记录创建的时间戳
UpdatedAt:记录最后更新的时间戳
DeletedAt:软删除时间戳,用于将记录标记为已删除,而不是从数据库中实际删除。
如果您不需要这个字段,您可以简单地使用:
db.Unscoped().
例如:
db.Unscoped().Where("param = ?", "param").Find(&YourStruct)
然后它将解决这个问题。
[我知道您已经解决了这个问题,但我为了其他遇到类似情况的人添加了这个说明]
英文:
This is due to your Table is not contain the relevant field "deleted_at" as you used the gorm.Model.
If you used gorm.Model, it will automatically integrate 4 fields as
ID: an auto-incrementing integer primary key
CreatedAt: a timestamp of when the record was created
UpdatedAt: a timestamp of when the record was last updated
DeletedAt: a soft delete timestamp used to mark the record as deleted instead of actually deleting it from the database.
If you do not need this, you can simply use
db.Unscoped().
Ex:
db.Unscoped().Where("param = ?", "param").Find(&YourStruct)
Then it will fix the issue.
[I know you already fix this issue, but i added this for any other who is facing for similar situations]
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论