我正在尝试使用它从我的数据库中获取一组项目,gorm它工作正常,我能够检索数据,但我只在数组中获取一个项目,而还有更多。这是我检索数组的代码。模型.gotype Address struct { ID uuid.UUID `json:"id" gorm:"primary_key;unique;not null"` Line string `gorm:"size:255;not null;column:line" json:"line"` Hostel string `gorm:"size:255;not null;column:hostel" json:"hostel"` CreatedAt time.Time `gorm:"default:CURRENT_TIMESTAMP;column:createdAt" json:"createdAt"` UpdatedAt time.Time `gorm:"default:CURRENT_TIMESTAMP;column:updatedAt" json:"updatedAt"` DeletedAt *time.Time `sql:"index;column:deletedAt" json:"deletedAt"`}type Addresses []Address数据库.gotype DbAddress struct { *model.Address}func (address *DbAddress) Get(db *gorm.DB) ([]model.Address, *errors.Error) { var err error addr := []model.Address{} err = db.Debug().Model(model.Address{}).Limit(100).Take(&addr).Error if gorm.IsRecordNotFoundError(err) { return nil, errors.NewNotFoundError(fmt.Sprintf("Address not found: %s", err.Error())) } if err != nil { return nil, errors.NewBadRequestError(fmt.Sprintf("error when trying to get Address: %s", err.Error())) } return addr, nil}服务.gofunc GetAddress() (model.Addresses, *errors.Error) { result := database.DbAddress{Address: &model.Address{}} return result.Get(database.DB)}控制器.gofunc GetAddress(c *gin.Context) { address, getErr := services.GetAddress() if getErr != nil { res.ResponseJSON(c, getErr.Status, nil, true, getErr.Message) return } res.ResponseJSON(c, http.StatusFound, address, false, "successfully got address data")}
1 回答
交互式爱情
TA贡献1712条经验 获得超3个赞
使用Find而不是Take.
// Get first record, order by primary key
db.First(&user)
//// SELECT * FROM users ORDER BY id LIMIT 1;
// Get one record, no specified order
db.Take(&user)
//// SELECT * FROM users LIMIT 1;
// Get last record, order by primary key
db.Last(&user)
//// SELECT * FROM users ORDER BY id DESC LIMIT 1;
// Get all records
db.Find(&users)
//// SELECT * FROM users;
// Get record with primary key (only works for integer primary key)
db.First(&user, 10)
//// SELECT * FROM users WHERE id = 10;
有关更多详细信息,请参阅:https ://gorm.io/docs/query.html
- 1 回答
- 0 关注
- 74 浏览
添加回答
举报
0/150
提交
取消